window.onload vs document.onload

Viewed 2300885

Which is more widely supported: window.onload or document.onload?

9 Answers

When do they fire?

window.onload

  • By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).

In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.

document.onload

  • It is called when the DOM is ready which can be prior to images and other external content is loaded.

How well are they supported?

window.onload appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced document.onload with window.onload.

Browser support issues are most likely the reason why many people are starting to use libraries such as jQuery to handle the checking for the document being ready, like so:

$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });

For the purpose of history. window.onload vs body.onload:

A similar question was asked on codingforums a while back regarding the usage of window.onload over body.onload. The result seemed to be that you should use window.onload because it is good to separate your structure from the action.

In short

  • window.onload is not supported by IE 6-8
  • document.onload is not supported by any modern browser (event is never fired)

window.onload   = () => console.log('window.onload works');   // fired
document.onload = () => console.log('document.onload works'); // not fired

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

Related