gpt4 book ai didi

javascript - 为什么JS脚本通常放在文档的头部?

转载 作者:行者123 更新时间:2023-11-28 11:07:52 25 4
gpt4 key购买 nike

为什么JS脚本通常放在文档的头部?是标准要求的,还是只是没有特殊原因的约定?

最佳答案

参见http://developer.yahoo.com/performance/rules.html#js_bottom

尽管过去的做法通常是将它们放在标题中,以便集中脚本和样式(等),但现在建议将脚本放在底部,以提高页面其余部分的加载速度.

引用:

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

关于javascript - 为什么JS脚本通常放在文档的头部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com