74

What is the difference between window.onload, document.onready and body.onload ?

alex
  • 479,566
  • 201
  • 878
  • 984
alter
  • 4,320
  • 7
  • 31
  • 36

1 Answers1

67

window.onload will wait until all assets have finished downloading, such as images and scripts.

DOM ready waits until you can access the DOM via the API.

As a side note, in this day and age, you ought to be using window.addEventListener('load', function() { }, false) or attachEvent() for older IEs.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    I think the DOM ready functionality of jQuery would also wait for scripts to load before firing wouldn't it? – screenm0nkey Apr 06 '11 at 13:52
  • But it cannot work for Chrome, Safari and Opera. Is there an alternative of `window.onload` for those browsers? – william Dec 01 '11 at 02:27
  • 3
    @william: `window.addEventListener('load', function() { }, false)`. – alex Dec 01 '11 at 02:40
  • Yes. `DOMContentLoaded` event from memory. – alex Aug 12 '12 at 01:18
  • What you mean by "in this day and age" is that it should be acceptable to defer script execution to onload on IE8 (since IE6-7 are more or less a thing of the past)? – Camilo Martin Oct 03 '12 at 17:35
  • @CamiloMartin I mean use the event handler systems besides `onevent` properties. – alex Dec 14 '12 at 11:27
  • @HiroProtagonist document.readyState and DOMContentLoaded are native to JavaScript – Christophe Feb 07 '13 at 17:55
  • Note that this won't let you know when the contents of an iFrame have loaded :) http://stackoverflow.com/questions/20572734/load-event-not-firing-when-iframe-is-loaded-in-chrome – Dean Rather Aug 04 '15 at 03:13