如果我将所有JavaScript放在页面底部,是否需要$(document).ready? [英] Is $(document).ready necessary if I put all my JavaScript at the bottom of the page?

查看:154
本文介绍了如果我将所有JavaScript放在页面底部,是否需要$(document).ready?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

jquery - $(document).ready是否必要?

将JS放在< / body> 标记之上会改善感知加载时间,因为浏览器在开始渲染之前不必读取和解析所有JS页面。

Putting the JS just above the </body> tag improves perceived load time because the browser doesn't have to read and parse through all the JS before it can start rendering the page.

但它有另一个好处,不是吗?我们不需要在 $(document).ready(function(){...})中包装JS,因为所有元素都已经在JS之上,因此已准备好进行操作。

But it has another benefit, doesn't it? We don't need to wrap the JS in $(document).ready(function() { ... }) because all the elements are already above the JS and thus are ready for manipulation.


  1. $(文件).ready 是否有必要确保DOM已完全加载并准备好进行操作?

  1. Is $(document).ready necessary to ensure the DOM has fully loaded and is ready for manipulation?

执行时间之间有什么区别吗?一种方法比另一种方法更快吗?

Is there any difference between the execution times? Would one method fire faster than the other?

我们可以链接我们的外部JS文件(< script src =...页面底部的/> 也是,或者是否需要在标题中?

Could we link our external JS files (<script src="..." />) at the bottom of the page too then, or does that need to be in the header?


推荐答案

这个SO答案说

stackoveflow问题

$(文件)。 ready是为了保证在调用函数时可以使用完整的DOM。
任何不依赖于DOM的功能和事件都不需要放入就绪事件。

$(document).ready is for assurance full DOM is available at the time the function is called. Any functions and events not depending on the DOM don't need to be put into the ready event.

此外 - 至提高页面渲染速度 - 以非阻塞方式动态加载JavaScript文件: http://berklee.github.com/ nbl / https://github.com/rgrove/lazyload/

Also - to improve page rendering speed - load javascript files dynamically in non-blocking fashion: http://berklee.github.com/nbl/ or https://github.com/rgrove/lazyload/

这种技术的工作原理如下:

This technique works somewhat like this:

 var script = document.createElement("script");
 script.type = "text/javascript";
 script.src = "file1.js";
 document.getElementsByTagName("head")[0].appendChild(script);

这个新元素加载源文件file1.js。一旦元素添加到页面,文件就开始下载。这项技术的重要之处在于,无论发起下载的位置如何,都可以下载并执行文件而不会阻止其他页面进程。您甚至可以将此代码放在文档的标题中,而不会影响页面的其余部分(除了用于下载文件的一个HTTP连接)。

This new element loads the source file file1.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated. You can even place this code in the header of a document without affecting the rest of the page (aside from the one HTTP connection that is used to download the file).

本书:Nickolas Zakas撰写的高性能JavaScript有很多关于JavaScript性能优化的有趣信息。

this book: "High Performance JavaScript" by Nickolas Zakas has a lot of interesting information about JavaScript performace optimization.

这篇关于如果我将所有JavaScript放在页面底部,是否需要$(document).ready?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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