应该JQuery代码在页眉或页脚

应该JQuery代码在页眉或页脚

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

问题描述

哪里是放置Jquery代码(或单独的Jquery文件)的最佳地点?如果将页面放在页脚中,页面加载速度会更快吗? 解决方案

所有脚本都应该最后加载几乎所有情况下,最好将所有脚本引用放在页面末尾,位于< / body> / code>。



如果由于模板问题和其他原因无法这样做,请使用 defer 属性修饰脚本标记以便浏览器知道在下载HTML后下载脚本:

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






边缘情况



然而,在页面加载期间,您可能会遇到页面闪烁或其他工件,通常可以通过将您的jQuery脚本引用置于< head> 标记,而无需 defer 属性。这些情况包括jQuery UI和其他插件,如jCarousel或Treeview,它们将DOM作为其功能的一部分来修改。

strong>进一步的注意事项



有些库必须在DOM或CSS之前加载,例如polyfills。 Modernizr就是这样一个库,它必须放置在头标记中。

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

解决方案

All scripts should be loaded last

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

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>


Edge cases

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.


Further caveats

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代码在页眉或页脚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 02:57