在 JavaScript 文件中包含 JavaScript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3991492/
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
Include a JavaScript file in a JavaScript file
提问by X10nD
Possible Duplicate:
How to include a JavaScript file in another JavaScript file?
I want to include a JavaScript file in a JavaScript file. include('filename.js');
is not working
我想在 JavaScript 文件中包含一个 JavaScript 文件。include('filename.js');
不管用
What is the right code?
什么是正确的代码?
采纳答案by FatherStorm
function includeJS(incFile)
{
document.write('<script type="text/javascript" src="'+ incFile+ '"></script>');
}
Then include a second JavaScript file by calling:
然后通过调用包含第二个 JavaScript 文件:
includeJS('filename.js');
回答by zod
Use:
用:
<script language="javascript" src="first.js"></script>
<script language="javascript" src="second.js"></script>
You can access the variables from the first file in the second file.
您可以从第二个文件中的第一个文件访问变量。
There isn't any need to include one JavaScript file into another. JavaScript code is globalised. You can include both the files in the HTML/JSP page.
没有必要将一个 JavaScript 文件包含到另一个文件中。JavaScript 代码是全球化的。您可以在 HTML/JSP 页面中包含这两个文件。
回答by Teja Kantamneni
Use document.write
in the first JavaScriptfunction:
使用document.write
在第一个JavaScript的功能:
document.write('<scr'+'ipt type="text/javascript" src="filename.js" ></scr'+'ipt>');
回答by Yasir
If you do the document.write method bear in mind that the code within the file will not be guaranteed to be loaded once document.write returns.
如果您使用 document.write 方法,请记住,一旦 document.write 返回,文件中的代码将无法保证被加载。
You may want to have some type of callback mechanism when the included file has loaded. That is, register a callback before document.write, and at the very end of your javascript file make a call to the callback function.
当包含的文件加载时,您可能需要某种类型的回调机制。也就是说,在 document.write 之前注册一个回调,并在你的 javascript 文件的最后调用回调函数。