不显眼的 JavaScript:<script>在 HTML 代码的顶部还是底部? [英] Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

查看:17
本文介绍了不显眼的 JavaScript:<script>在 HTML 代码的顶部还是底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了 Yahoo 宣言加快网站速度的最佳实践.他们建议尽可能将 JavaScript 包含放在 HTML 代码的底部.

I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.

但具体在哪里,什么时候?

But where exactly and when?

我们应该把它放在关闭 </html> 之前还是之后?最重要的是,我们什么时候还应该把它放在 部分?

Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?

推荐答案

真正不引人注目的脚本有两种可能性:

There are two possibilities for truly unobtrusive scripts:

  • 通过头部部分中的脚本标记包含外部脚本文件
  • 通过正文底部的脚本标签包含一个外部脚本文件(在</body></html>之前)

第二个可以更快,因为最初的雅虎研究表明,一些浏览器会在点击脚本标签时尝试加载脚本文件,因此在完成之前不会加载页面的其余部分.但是,如果您的脚本有一个就绪"部分,它必须在 DOM 准备好后立即执行,您可能需要将它放在头中.另一个问题是布局 - 如果您的脚本要更改页面布局,您希望它尽早加载,这样您的页面就不会在用户面前花费很长时间重新绘制.

The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.

如果外部脚本站点在另一个域(如外部小部件)上,可能值得将其放在底部以避免延迟页面加载.

If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.

对于任何性能问题,做你自己的基准测试 - 当一项研究完成时,可能会随着你自己的本地设置或浏览器的变化而改变.

And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.

这篇关于不显眼的 JavaScript:&lt;script&gt;在 HTML 代码的顶部还是底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆