< head>中的JavaScript或仅仅在< / body>之前? [英] JavaScript in <head> or just before </body>?

查看:91
本文介绍了< head>中的JavaScript或仅仅在< / body>之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即将开始一个新的Web项目,并计划将我的JS脚本放在头部和尾部使用以下方案:


  1. 对于页面用户体验至关重要的脚本是头等大事。正如我仔细阅读网页 - 头部中的脚本在页面加载之前加载,因此将用户体验所必需的脚本放在那里是有意义的。


  2. 页面的设计和用户体验(Google Analytics脚本等)不重要的脚本位于< / body> 之前。


这是一种明智的做法吗? b
$ b

将所有脚本放在< head> 中,然后将延迟属性添加到非必要的脚本中 - 但是我读过旧版本的FF不会选择up the defer attribute。

解决方案

我想很多开发人员在< /



然而,如果你正确地组织你的代码,页面无关紧要。



例如,当使用jQuery时,您可以通过执行以下操作来确保代码不会运行,直到页面及其元素完全呈现:

  $(document ).ready(function(){
// Code here
});

然后,脚本引用可以放在头部< / body>之前引用脚本标记。 。这可以防止在脚本加载时渲染阻塞,并且对于站点感知速度更好。



使用此技术时不应使用突兀的JavaScript。


I am about to embark on a new web project and I plan to put my JS-scripts in the head and before end-body using the following scheme:

  1. Scripts that are essential for the UX of the page goes in the head. As I've picked up perusing the web - scripts in the head is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.

  2. Scripts that are non-essential to the design and UX (Google Analytics scripts etc.) of the page goes before the </body>.

Is this a sensible approach?

Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts - however I've read that older versions of FF doesn't pick up the defer attribute.

解决方案

I think a lot of developers run javascript just before the </body> so that it is ran after all the elements have been rendered.

However, if you organise your code correctly, the position on the page doesn't matter.

For example, when using jQuery, you can ensure the code isn't ran until the page and its elements are fully rendered by doing the following:

$(document).ready(function(){
   //Code here
});

Then the script reference can be put in the head tag.


Update - Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.

No obtrusive javascript should be used when using this technique.

这篇关于&lt; head&gt;中的JavaScript或仅仅在&lt; / body&gt;之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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