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

发布于 2024-12-21 17:13:54 字数 283 浏览 0 评论 0原文

可以使用

$('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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷爱 2024-12-28 17:13:54

$('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.

国粹 2024-12-28 17:13:54

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

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

或者,更简洁和惯用:

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

“load”处理程序确实与实际事件相关,并且可以按几种不同的类型进行处理元素的数量:例如 。当页面的所有资源被加载时,文档或窗口级别的“加载”事件就会发生。然而,(在某些浏览器中合成的)“ready”事件发生在页面 DOM 准备就绪时,但可能发生在 内容之前。

另一种选择是简单地将

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文