When to use "window.onload"?

Jonathan Lam picture Jonathan Lam · Nov 24, 2013 · Viewed 80.6k times · Source

In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?

For example, if I want to have a pop-up, should I write (directly inside the <script> tag):

alert("hello!");

Or:

window.onload = function() {
    alert("hello!");
}

Both appear to run just after the page is loaded. What is the the difference?

Answer

Crayon Violent picture Crayon Violent · Nov 24, 2013

window.onload just runs when the browser gets to it.

window.addEventListener waits for the window to be loaded before running it.

In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:

window.addEventListener('load', 
  function() { 
    alert('hello!');
  }, false);