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

半世苍凉 提交于 2019-12-18 01:58:08

问题


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

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

});

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

}

回答1:


Depends on what you want to do.

  • 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.

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);



回答2:


Yes, window.onload allows you to have only one listener. jQuery ready attaches as many listeners as you want.




回答3:


Windows.onload will wait for everything to load on a page including images. Document.ready will fire as soon as soon as the html is loaded.



来源:https://stackoverflow.com/questions/21742867/jquery-ready-vs-window-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!