当 javascript 文件全部合并为一个文件时,它们的顺序是否重要?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4987977/
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
Does the ORDER of javascript files matter, when they are all combined into one file?
提问by Sam
In todays modern age, where lots of (popular) javascripts files are loaded externally and locally, does the order in which the javascripts files are calledmatter especially when all local files are all combined (minified) into one file?
在当今的现代时代,许多(流行的)javascripts 文件在外部和本地加载,调用 javascripts 文件的顺序是否重要,尤其是当所有本地文件都合并(缩小)为一个文件时?
Furthermore, many claim that Javascript should go in the bottom of the pagewhile others say javascript is best left in the head. Which should one do when? Thanks!
此外,许多人声称 Javascript 应该放在页面底部,而其他人则说 javascript 最好留在页面底部。哪个应该在什么时候做?谢谢!
google cdn latest jquery js | external
another cdn loaded javascript js | external
TabScript ...js \
GalleryLightbox ...js \
JavascriptMenu ...js \
HTMlFormsBeautifier ...js > all minified and combined into one .js file!
TextFieldResize ...js /
SWFObjects ...js /
Tooltips ...js /
CallFunctions ...js /
回答by jmort253
Order matters in possibly one or more of the following situations:
订单可能在以下一种或多种情况下很重要:
- When one of your scripts contains dependencies on another script.
If the script is in the BODY and not the HEAD.. UPDATE:HEAD vs BODY doesn't seem to make a difference. Order matters. Period.- When you are running code in the global namespace that requires a dependency on another script.
- 当您的一个脚本包含对另一个脚本的依赖时。
如果脚本在 BODY 而不是 HEAD 中。. 更新:HEAD 与 BODY 似乎没有什么区别。订单很重要。时期。- 当您在需要依赖另一个脚本的全局命名空间中运行代码时。
The best way to avoid these problems is to make sure that code in the global namespace is inside of a $(document).ready()
wrapper. Code in the global namespace must be loaded in the order such that executed code must first be defined.
避免这些问题的最佳方法是确保全局命名空间中的代码位于$(document).ready()
包装器内。全局命名空间中的代码必须按照必须首先定义执行的代码的顺序加载。
Checking the JavaScript error console in Firebug or Chrome Debugger can possibly tell you what is breaking in the script and let you know what needs to be modified for your new setup.
在 Firebug 或 Chrome Debugger 中检查 JavaScript 错误控制台可能会告诉您脚本中发生了什么问题,并让您知道需要为新设置修改哪些内容。
Order generally doesn't matter if functions are invoked based on events, such as pageload, clicks, nodes inserted or removed, etc. But if function calls are made outside of the events in the global namespace, that is when problems will arise. Consider this code:
如果函数是基于事件调用的,例如页面加载、点击、节点插入或删除等,则顺序通常无关紧要。但是如果函数调用是在全局命名空间中的事件之外进行的,那么就会出现问题。考虑这个代码:
JS file: mySourceContainingEvilFunctionDef.js
JS 文件:mySourceContainingEvilFunctionDef.js
function evilGlobalFunctionCall() {
alert("I will cause problems because the HTML page is trying to call " +
"me before it knows I exist... It doesn't know I exist, sniff :( ");
}
HTML:
HTML:
<script>
evilGlobalFunctionCall(); // JS Error - syntax error
</script>
<!-- Takes time to load -->
<script type="text/javascript" src="mySourceContainingEvilFunctionDef.js"></script>
...
In any case, the above tips will help prevent these types of issues.
无论如何,上述提示将有助于防止这些类型的问题。
As a side note, you may want to consider that there are certain speed advantages to utilizing the asynchronous nature of the browser to pull down resources. Web browsers can have up to 4 asynchronous connections open at a time, meaning that it's quite possible that your one massive script might take longer to load than that same script split up into chunks! There is also Yahoo Researchthat shows combining scripts produces the faster result, so results vary from one situation to another.
作为旁注,您可能需要考虑利用浏览器的异步特性来下拉资源具有一定的速度优势。Web 浏览器一次最多可以打开 4 个异步连接,这意味着您的一个庞大的脚本很可能比拆分成块的同一个脚本需要更长的时间来加载!还有雅虎研究表明组合脚本产生更快的结果,因此结果因情况而异。
Since it's a balance between the time taken to open and close several HTTP connections vs the time lost in limiting yourself to a single connection instead of multiple asynchronous connections, you may need to do some testing on your end to verify what works best in your situation. It may be that the time taken to open all of the connections is offset by the fact that the browser can download all the scripts asynchronously and exceed the delays in opening/closing connections.
由于打开和关闭多个 HTTP 连接所花费的时间与将自己限制为单个连接而不是多个异步连接所损失的时间之间存在平衡,因此您可能需要在自己的一端进行一些测试以验证哪种方式最适合您的情况. 打开所有连接所花费的时间可能被浏览器可以异步下载所有脚本并超过打开/关闭连接的延迟这一事实抵消了。
With that said, in most cases, combining the script will likely result in the fastest speed gains and is considered a best practice.
话虽如此,在大多数情况下,组合脚本可能会带来最快的速度提升,被认为是最佳实践。
回答by alex
Yes, depending very much on what you do.
是的,很大程度上取决于你做什么。
For example, if a.js
had...
例如,如果a.js
有...
var a = function() {
alert('a');
}
...and b.js
had...
......并且b.js
有......
a()
...then you wouldn't want to include b.js
before a.js
, or a()
won't be available.
...那么您不想包含b.js
before a.js
,或者a()
将不可用。
This only applies to function expressions; declarations are hoisted to the top of their scope.
这仅适用于函数表达式;声明被提升到其作用域的顶部。
As for whether you should combine jQuery, I reckon it would be better to use the Google hosted copy - adding it to your combined file will make it larger when there is a great chance the file is already cached for the client.
至于你是否应该结合 jQuery,我认为最好使用 Google 托管的副本 - 当文件很有可能已经为客户端缓存时,将它添加到你的组合文件中会使其更大。
回答by Jannes
Read this post from the webkit teamfor some valuable information about how browsers load and execute script files.
阅读来自 webkit 团队的这篇文章,了解有关浏览器如何加载和执行脚本文件的一些有价值的信息。
Normally when the parser encounters an external script, parsing is paused, a request is issued to download the script, and parsing is resumed only after the script has fully downloaded and executed.
通常,当解析器遇到外部脚本时,会暂停解析,发出下载脚本的请求,只有在脚本完全下载并执行完毕后才会恢复解析。
So normally (without those async or defer attributes), scripts get excutedin the order in which they are specified in the source code. Butif the script tags are in the <head>
, the browser will first wait for all scripts to load before it starts executinganything.
所以通常(没有那些 async 或 defer 属性),脚本会按照它们在源代码中指定的顺序执行。但是如果脚本标签在 中<head>
,浏览器将首先等待所有脚本加载完毕,然后才开始执行任何操作。
This means that it makes no difference if the script is splitted into multiple files or not.
这意味着脚本是否拆分为多个文件没有区别。
回答by Jannes
If you have two files that define variables or functions with the same name, the order that they're included will change which one actually is defined
如果您有两个文件定义了同名的变量或函数,则它们包含的顺序将更改实际定义的一个
回答by Andrew Noyes
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
如果我理解您的问题,我认为您是在问在文件中定义函数/方法的位置是否重要,答案是否定的,您可以在单个源文件中的任何位置定义它们。JavaScript 解析器将在尝试运行代码之前读取所有符号。