Javascript 在 .js 文件中包含 .js 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2145914/
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
Including a .js file within a .js file
提问by Yo Momma
I'd like to know if it is possible to include a .jsfile within another .jsfile?
我想知道是否可以.js在另一个.js文件中包含一个文件?
The reason for me wanting to do this is to keep client includes to a minimum. I have several .jsfiles already written with functions that are needed by the client. The client would have an html file which he/she manages with a .jsfile include (my .jsfile).
我想要这样做的原因是将客户包括在最低限度。我.js已经用客户端所需的函数编写了几个文件。客户将有一个 html 文件,他/她使用.js文件包含(我的.js文件)管理该文件。
I could re-write a new .jsfile with all the functions in it or, to avoid doing double work, figure out a way to write a .jsfile that includes other .jsfiles.
我可以重新编写一个.js包含所有函数的新文件,或者为了避免重复工作,找出一种方法来编写.js包含其他.js文件的文件。
采纳答案by YOU
I basically do like this, create new element and attach that to <head>
我基本上喜欢这样,创建新元素并将其附加到 <head>
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
You may also use onloadevent to each script you attach, but please test it out, I am not so sure it works cross-browser or not.
您也可以onload对附加的每个脚本使用事件,但请对其进行测试,我不太确定它是否可以跨浏览器工作。
x.onload=callback_function;
回答by gnarf
The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.
浏览器加载时间的最佳解决方案是使用服务器端脚本将它们全部连接到一个大的 .js 文件中。确保 gzip/缩小最终版本。单一请求 - 漂亮而紧凑。
Alternatively, you can use DOM to create a <script>tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the loadevent on that script tag.
或者,您可以使用 DOM 创建<script>标签并在其上设置 src 属性,然后将其附加到<head>. 如果您需要等待该功能加载,您可以让您的 javascript 文件的其余部分从该load脚本标记上的事件中调用。
This function is based on the functionality of jQuery $.getScript()
此功能基于jQuery的功能 $.getScript()
function loadScript(src, f) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
var done = false;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
if (typeof f == 'function') f();
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
// example:
loadScript('/some-other-script.js', function() {
alert('finished loading');
finishSetup();
});
回答by rAm
There is no straight forward way of doing this.
没有直接的方法可以做到这一点。
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
您可以做的是按需加载脚本。(再次使用类似于 Ignacio 提到的内容,但更简洁)。
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
查看此链接以了解执行此操作的多种方法:http: //ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
我最喜欢的是(并不总是适用):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
谷歌的关闭也提供了类似的功能。
回答by Daniel Vassallo
A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.
解决从 HTML 文件中减少 JavaScript 引用问题的一种流行方法是使用像Sprockets这样的连接工具,它可以预处理 JavaScript 源文件并将其连接在一起。
Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.
除了减少来自 HTML 文件的引用数量外,这还将减少对服务器的点击次数。
You may then want to run the resulting concatenation through a minification tool like jsminto have it minified.
然后,您可能希望通过jsmin之类的缩小工具运行生成的串联以将其缩小。
回答by Pete Jordan
I use @gnarf's method, though I fall back on document.writelning a <script>tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:
我使用@gnarf 的方法,尽管我回过头document.writeln来<script>为 IE<7 标记一个标签,因为我无法让 DOM 创建在 IE6 中可靠地工作(而且 TBH 并不在意投入太多精力)。我的代码的核心是:
if (horus.script.broken) {
document.writeln('<script type="text/javascript" src="'+script+'"></script>');
horus.script.loaded(script);
} else {
var s=document.createElement('script');
s.type='text/javascript';
s.src=script;
s.async=true;
if (horus.brokenDOM){
s.onreadystatechange=
function () {
if (this.readyState=='loaded' || this.readyState=='complete'){
horus.script.loaded(script);
}
}
}else{
s.onload=function () { horus.script.loaded(script) };
}
document.head.appendChild(s);
}
where horus.script.loaded()notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).
其中horus.script.loaded()注意到 javascript 文件已加载,并调用任何挂起的未调用例程(由自动加载器代码保存)。

