Jquery 代码应该放在页眉还是页脚? [英] Should Jquery code go in header or footer?

查看:27
本文介绍了Jquery 代码应该放在页眉还是页脚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

放置 Jquery 代码(或单独的 Jquery 文件)的最佳位置在哪里?如果我把它放在页脚,页面加载会更快吗?

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?

推荐答案

所有脚本都应该最后加载

在几乎所有情况下,最好将所有脚本引用放在页面末尾,就在 </body> 之前.

In just about every case, it's best to place all your script references at the end of the page, just before </body>.

如果由于模板问题等原因无法执行此操作,请使用 defer 属性装饰您的脚本标签,以便浏览器知道在下载 HTML 后下载您的脚本:

If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:

<script src="my.js" type="text/javascript" defer="defer"></script>

<小时>

边缘案例

但是,在某些极端情况下,您可能会在页面加载过程中遇到页面闪烁或其他伪影,通常只需将 jQuery 脚本引用放在 <head> 标记中即可解决.em>没有 defer 属性.这些案例包括 jQuery UI 和其他插件,例如 jCarousel 或 Treeview,它们修改 DOM 作为其功能的一部分.

There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.

进一步的注意事项

有些库必须在 DOM 或 CSS 之前加载,例如 polyfills.Modernizr 就是这样一个库,必须放在 head 标签中.

There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.

这篇关于Jquery 代码应该放在页眉还是页脚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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