我应该使用 window.load 还是 document.ready jquery
可以使用
$('document').ready(function() {
//Do Code
});
or
$('window').load(function() {
//Do Code
});
最近我发现jQuery
。然而,它们对我来说似乎是一样的!但显然不是。
所以我的问题是:对于基于动画和异步的网站,我应该使用哪一个?通常,这两者中哪一种更好用?
谢谢。
Recently I saw that you could use either
$('document').ready(function() {
//Do Code
});
or
$('window').load(function() {
//Do Code
});
for 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$('document').ready
在 DOM 准备就绪时运行代码,但在页面本身已加载时运行代码,即网站尚未绘制并且图片等内容尚未加载。$(window).load
在绘制页面并加载所有内容后运行代码。当您需要获取图像的大小时,这会很有帮助。如果图像没有样式或宽度/高度,则除非使用$(window).load
,否则无法获取其大小。$('document').ready
runs 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.$(window).load
runs 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
.首先,您可能需要考虑使用“ready”事件,您可以像这样处理它:
或者,更简洁和惯用:
“load”处理程序确实与实际事件相关,并且可以按几种不同的类型进行处理元素的数量:例如
和
。当页面的所有资源被加载时,文档或窗口级别的“加载”事件就会发生。然而,(在某些浏览器中合成的)“ready”事件发生在页面 DOM 准备就绪时,但可能发生在
内容之前。
另一种选择是简单地将
标记放在
的最末尾,甚至放在
之后>。这样,脚本就可以使用整个 DOM,但您不必担心任何类型的事件处理即可知道这一点。
Well first of all you may want to consider using the "ready" event, which you can handler like this:
Or, more succinctly and idiomatically:
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.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.