javascript 我应该使用 window.load 还是 document.ready jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8562609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:49:06  来源:igfitidea点击:

Should I use window.load or document.ready jquery

javascriptjqueryloadwindowdocument

提问by H Bellamy

Recently I saw that you could use either

最近我看到你可以使用

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

or

或者

$('window').load(function() {
//Do Code
});

for jQuery.

对于 jQuery。

However, they seem the same to me! But clearly aren't.

然而,它们在我看来是一样的!但显然不是。

So my question is: Which one should I use for a website sort of based on animation and async? And also which one of the two is generally better to use?

所以我的问题是:对于基于动画和异步的网站,我应该使用哪个?以及两者中的哪一个通常更好用?

Thanks.

谢谢。

回答by Einar ólafsson

$('document').readyruns the code when the DOM is ready, but not when the page itself has loaded, that is, the site has not been painted and content like images have not been loaded.

$('document').ready当 DOM 准备好时运行代码,而不是在页面本身加载时运行代码,即站点尚未绘制且图像等内容尚未加载。

$(window).loadruns the code when the page has been painted and all content has been loaded. This can be helpful when you need to get the size of an image. If the image has no style or width/height, you can't get its size unless you use $(window).load.

$(window).load当页面被绘制并且所有内容都已加载时运行代码。当您需要获取图像的大小时,这会很有帮助。如果图像没有样式或宽度/高度,除非使用$(window).load.

回答by Pointy

Well first of all you may want to consider using the "ready" event, which you can handler like this:

首先,您可能要考虑使用“就绪”事件,您可以像这样处理它:

$().ready(function() {
  ...
});

Or, more succinctly and idiomatically:

或者,更简洁、更地道:

$(function() {
  ...
});

The "load" handler really relates to an actual event, and can be handled on several different sorts of elements: <img>and <iframe>for example. The "load" event at the document or window level happens when all of the page's resources are loaded. The (synthesized, in some browsers) "ready" event however happens when the page DOM is ready but possibly before things like <img>contents.

的“负载”处理程序确实涉及实际事件,并且可以在几个不同种类的元素进行处理:<img><iframe>例如。当页面的所有资源都被加载时,文档或窗口级别的“加载”事件就会发生。然而,(在某些浏览器中合成的)“就绪”事件发生在页面 DOM 准备就绪时,但可能发生在诸如<img>内容之类的事情之前。

Another option is to simply put your <script>tags at the very end of the <body>or even after the <body>. That way the scripts have the entire DOM to work with, but you don't have to worry about any sort of event handling to know that.

另一种选择是简单地把你的<script>标签在的尽头<body>,甚至之后<body>。这样脚本就可以使用整个 DOM,但您不必担心任何类型的事件处理来了解这一点。