Jquery .ready()vs window.onload [英] Jquery .ready() vs window.onload

查看:104
本文介绍了Jquery .ready()vs window.onload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在window.onload上使用Jquery ready()函数有什么好处吗?

Are there any advantages of using the Jquery ready() function over window.onload?

// Jquery ready
$(document).ready(function() {

});

// window.onload
window.onload = function () {

}


推荐答案

取决于你想做什么。


  • jQuery ready将在HTML准备就绪时运行您的代码,但在图像和其他资源完成之前。这是您可以使用JavaScript更改DOM的最早时间,因此它被广泛使用。 (在现代浏览器中,它被原生事件 DOMContentLoaded取代 )。

  • window.onload load event)在一切已完成加载。图像,Flash和一些脚本,但通常不是样式表。将此选项用于仅在页面不再更改时才能运行的代码。

  • jQuery ready will run your code when the HTML is all ready, but before images and other resources have finished. This is the earliest possible time that you can change the DOM with JavaScript, so it's widely used. (In modern browsers it's replaced by the native event DOMContentLoaded).
  • window.onload (the load event) runs after everything has finished loading. Images, Flash, and some scripts, but usually not stylesheets. Use this for code that should run only when the page won't change any more.

此外,使用 window.onload 你只能附加一个监听器,但你可以随意添加jQuery。要在 window.onload 上附加多个事件,请使用 addEventListener

Also, with window.onload you can only attach one listener, but you can attach as many as you want with jQuery ready. To attach more than one event on window.onload, use addEventListener:

window.addEventListener('load', function () {

}, false);

这篇关于Jquery .ready()vs window.onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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