<head> 中的 JavaScript还是就在 &lt;/body&gt; 之前? [英] JavaScript in &lt;head&gt; or just before &lt;/body&gt;?

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

问题描述

我即将开始一个新的网络项目,我计划在 <head></body> 之前放一些 JavaScript,使用以下方案:

  1. 对页面用户体验至关重要的脚本:在 中.正如我已经开始仔细阅读网络 - <head> 中的脚本在页面加载之前加载,因此将用户体验必不可少的脚本放在那里是有意义的.p>

  2. 对设计和用户体验不重要的脚本(Google Analytics 脚本等):在 </body> 之前.

这是一种明智的做法吗?

另一种方法是将所有脚本放在 中,并将 defer 属性添加到非必要脚本中.但是,我读到旧版本的 Firefox 没有选择 defer 属性.

解决方案

我认为很多开发人员在 </body> 之前运行 JavaScript,以便它在所有元素都完成之后运行已呈现.

但是,如果您正确组织代码,则页面上的位置并不重要.

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

$(document).ready(function(){//代码在这里});

然后脚本引用可以放在head标签中.


脚本标签应该在 </body> 之前引用.这可以防止在脚本加载时呈现阻塞,并且对站点感知速度更好.

在使用此技术时不应使用干扰性的 JavaScript.

I am about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:

  1. Scripts that are essential for the UX of the page: 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.): 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 read that older versions of Firefox don't pick up the defer attribute.

解决方案

I think a lot of developers run JavaScript just before the </body> so that it is run 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 run 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.


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.

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

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