When to use "window.onload"?

JavascriptOnloadOnload Event

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

The other answers all seem out of date

First off, putting scripts at the top and using window.onload is an anti-pattern. It's left over from IE days at best or mis-understandings of JavaScript and the browser at worst.

You can just move your scripts the the bottom of your html

<html>
  <head>
   <title>My Page</title>
  </head> 
  <body>
    content
  </body>
  <script src="some-external.js"></script>
  <script>
    some in page code
  </script>
</html>

The only reason people used window.onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.

The hacky workaround was to use window.onload to wait for the rest of the page to load. Moving your script to the bottom also solved that issue and now there's no need to use window.onload since your body and content will have already been loaded.

The more modern solution is to use the defer tag on your scripts but to use that your scripts need to all be external.

<head>
    <script src="some-external.js" defer></script>
    <script src="some-other-external.js" defer></script>
</head>

This has the advantage that the browser will start downloading the scripts immediately and it will execute them in the order specified but it will wait to execute them until after the page has loaded, no need for window.onload or the better but still unneeded window.addEventListener('load', ...

Solution 2 - Javascript

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);

Solution 3 - Javascript

Here's the documentation on MDN.

According to it:

> The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

Your first snippet of code will run as soon as browser hit this spot in HTML.

The second snippet will trigger popup when the DOM and all images are fully loaded (see the specs).

Considering the alert() function, it doesn't really matter at which point it will run (it doesn't depend on anything besides window object). But if you want to manipulate the DOM - you should definitely wait for it to properly load.

Solution 4 - Javascript

That depends on if you want it to run when the script element is encountered or if you want it to run when the load event fires (which is after the entire document (including such things as images) has loaded).

Neither is always right.

In general, however, I'd avoid assigning functions directly to onload in favour of using addEventListener (with compatibility libraries if I needed to support older browsers).

Solution 5 - Javascript

The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.

document.ready is a great alternative to window.onload if you're using jQuery.

See here: https://stackoverflow.com/questions/3698200/window-onload-vs-document-ready

Solution 6 - Javascript

You have three alternatives:

  1. Directly inside the script tag runs it as soon as it is parsed.

  2. Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.

  3. Inside window.onload function(){}) will run as soon as all page resources are loaded.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan LamView Question on Stackoverflow
Solution 1 - JavascriptgmanView Answer on Stackoverflow
Solution 2 - JavascriptCrayon ViolentView Answer on Stackoverflow
Solution 3 - JavascriptSlava Fomin IIView Answer on Stackoverflow
Solution 4 - JavascriptQuentinView Answer on Stackoverflow
Solution 5 - JavascriptSeeMeCodeView Answer on Stackoverflow
Solution 6 - JavascriptHenrikView Answer on Stackoverflow