Skip to content
Advertisement

When to use “window.onload”?

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement