22

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

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

});

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

}
James
  • 1,873
  • 3
  • 22
  • 28
  • 2
    well for starters, using the jQuery version won't overwrite other code efforts to attach something to a load state. But in any case, `document.ready` is not the same event as `window.onload` – CrayonViolent Feb 13 '14 at 00:26
  • 1
    This question has a better answer than the one linked to as the original. – nroose Feb 19 '16 at 23:06

3 Answers3

40

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);
rvighne
  • 20,755
  • 11
  • 51
  • 73
2

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

Elie
  • 6,915
  • 7
  • 31
  • 35
2

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.

Papa
  • 1,628
  • 1
  • 11
  • 16