在 .js 文件中使用外部 javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2579883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using external javascript files in a .js file
提问by David Menard
I would like to use an external javascript file in another javascript file. For example, I could store all my global variables in a globals.js file and then call then from the website logic logic.js. Then in the index.html, i would insert the tag. How do I use the globals.js inside the logic.js?
我想在另一个 javascript 文件中使用外部 javascript 文件。例如,我可以将所有全局变量存储在 globals.js 文件中,然后从网站逻辑 logic.js 中调用。然后在 index.html 中,我会插入标签。如何在 logic.js 中使用 globals.js?
采纳答案by Marc B
Javascript doesn't have any implicit "include this other file" mechanisms, like css's @include. You just have to list your globals file before the logic file in the tags:
Javascript 没有任何隐含的“包含其他文件”机制,例如 css 的 @include。你只需要在标签中的逻辑文件之前列出你的全局文件:
<script type="text/javascript" src="globals.js" />
<script type="text/javascript" src="logic.js" />
If guaranteeing that the globals are available before anything in the logic file fires up, you can do a slow polling loop to see if some particular variable is available before calling an init() or whatever function.
如果确保在逻辑文件中的任何内容启动之前全局变量可用,您可以执行一个慢速轮询循环,以在调用 init() 或任何函数之前查看某些特定变量是否可用。
回答by Marc B
function loadExternalJS(TARGET_URL){
var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xhr.open('GET', TARGET_URL, false);
xhr.send(null);
var code = xhr.responseText;
var dScript = document.createElement('script');
try {
dScript.appendChild( document.createTextNode(parsed) );
document.body.appendChild(dScript);
} catch(e) {
dScript.text = parsed;
document.getElementsByTagName('head')[0].appendChild(dScript);
}
xhr = null;
回答by tloflin
document.write('<script type="text/javascript" src="globals.js"></script>');
Edit: Actually, this probably won't work for your purposes, as global.js variables won't be accessible until logic.js completes. You may be able to wrap logic.js in a function that is called after global.js loads. Otherwise I don't think there is a way to do what you're asking.
编辑:实际上,这可能不适用于您的目的,因为在 logic.js 完成之前无法访问 global.js 变量。您可以将 logic.js 包装在一个在 global.js 加载后调用的函数中。否则,我认为没有办法做到你所要求的。
回答by ZippyV
Just make sure both files are referenced in your index.html.
只要确保在 index.html 中引用了这两个文件。
回答by smulholland2
You can also do something like this:
你也可以做这样的事情:
$(document).ready(function(){
$('body').append($('<script src="/path/to/script/foo.min.js"></script>'));
});
Just use that line before you need to reference something in the included js file.
在需要引用包含的 js 文件中的某些内容之前,只需使用该行。

