不引人注目的JavaScript:< script>在HTML代码的顶部或底部? [英] Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

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

问题描述

我最近阅读了雅虎的声明加速您的网站的最佳做法。他们建议尽可能将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.

但是在何时何地?

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

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> )

  • including an external script file via a script tag in the head section
  • including an external script file via a script tag at the bottom of the body (before </body></html>)

第二个可以更快,因为原来的雅虎研究表明,一些浏览器尝试加载脚本文件时,因此不会加载页面的其余部分,直到它们完成。但是,如果你的脚本有一个ready部分,必须在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天全站免登陆