为什么JS脚本通常放在文档的头部?
为什么JS脚本通常放在文档的头部?是标准要求的,还是只是没有特殊原因的约定?
Why are JS scripts usually place in the header of a document? Is it required by standards, or is it just a convention with no particular reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅http://developer.yahoo.com/performance/rules.html#js_bottom
虽然过去的做法通常是将它们放在页眉中,以便集中脚本和样式(等),但现在建议将脚本放在底部,以提高页面其余部分的加载速度。
引用:
See http://developer.yahoo.com/performance/rules.html#js_bottom
Although past practice has often been to place them in the header for the sake of centralizing scripts and styles (and the like), it is advisable now to place the scripts at the bottom to improve loading speed of the rest of the page.
To quote:
这取决于脚本正在做什么。如果您的代码包含在 onLoad 事件中,那么没关系,因为它几乎会立即返回并且不会阻塞,否则您应该将其放在合适的位置,因为位置确实很重要。
至于把它放在最后,确实给了用户一些额外的时间来开始查看页面。只需问自己一个问题 - 我的网站可以在没有 JavaScript 的情况下运行吗?如果没有,那么在我看来,将它放在哪里并不重要,因为 onLoad 代码只会在 DOM 完全加载(包括图像等二进制内容)时执行。如果你可以在没有 JavaScript 的情况下使用它,那么把它放在最后,这样图像可以更快地加载。
另请注意,大多数 JS 库使用特殊代码来解决 onLoad 问题,并为此使用自定义事件,一旦 DOM 加载,该事件就会被触发,并且不会等待二进制数据。
现在我写完了所有这些,我有一个自己的问题。使用 jQuery
并将 script 标记放在页面末尾是否与使用 onLoad 事件并将其放在开头相同?
它应该是相同的,因为浏览器会在加载列表中最后一个脚本之前加载所有图像。如果你知道答案请发表评论(我太懒了,现在测试它已经太晚了)。
It depends on what the script is doing. If your code is wrapped in onLoad event then it doesn't matter since it will return almost immediately and not block otherwise you should put it where it fits because the placement does matter.
As for putting it at the end, it does give a little extra time for user to start looking at the page. Just ask yourself a question - does my site work without javascript? If it doesn't, then in my opinion it doesn't mater where you put it since onLoad code will only be executed when the DOM has been fully loaded (that includes binary content like images). If you can use it without javascript then put it at the end so that images can load faster.
Also note that most JS libraries use special code which works around the onLoad problem and uses custom event for this which gets fired once DOM has loaded and doesn't wait for binary data.
Now that I wrote all that, I got a question of my own. Does using say jQuery's
and putting the script tag at the end of page is the same as using onLoad event and putting it at the start?
It should be the same because browser would load all images before loading the script which is the last one in the list. If you know the answer leave a comment (I'm too lazy and it's too late to test it atm).
这只是一个约定。通常建议将脚本放在正文的末尾,以便页面可以在加载它们之前显示,这始终是一个优点。此外,在加载文档或将脚本放入正文之前,
document.body
无法使用。It's just a convention. It's usually recommended to put scripts at the end of the body so the page can display before loading them, which is always a plus. Also,
document.body
can't be used until the document is loaded or if you put the script in the body.