Zack Gao
Zack Gao

Reputation: 568

How do you determine the firing order of load and DOMContentLoaded events?

Why does the below code (JS Bin) fire in the order 1, 5, 3, 4? And why does 2 not fire at all?

According to the answer to this question, "4" should fire before "5". That's not what is shown by the order of the alerts. However, if I change the body and img onload handlers to execute document.write instead of alert, then 5 will be displayed, which is consistent with that answer.

<!DOCTYPE html>
<html>
    <head>
      <script>
        document.addEventListener("DOMContentLoaded", function() {
          alert("1");
        });
        document.addEventListener("load", function() {
          alert("2");
        });
        window.addEventListener("load", function() {
          alert("3");
        });
      </script>
    </head>
    <body onload="alert('4')">
        <h1>Hello World!</h1>
        <img onload="alert('5')" src="https://developer.cdn.mozilla.net/media/redesign/img/logo_sprite.svg?2014-01" alt="Smiley face" width="42" height="42" />
    </body>
</html>

Upvotes: 3

Views: 2491

Answers (1)

epascarello
epascarello

Reputation: 207511

window/body onload fires after all the images are loaded.

From MDN window.onload

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, scripts, links and sub-frames have finished loading.

So window load should come after the image load is fired.

And order of window/body events being triggeed depends on when you register the event listeners

<!DOCTYPE html>
<html>
    <head>
      <script>
        document.addEventListener("DOMContentLoaded", function() {
          console.log("Head - DOMContentLoaded");
        });
        document.addEventListener("load", function() {
          console.log("head - document load");
        });
        window.addEventListener("load", function() {
          console.log("head - window load");
        });
      </script>
    </head>
    <body onload="console.log('BODY ONLOAD')">
        <h1>Hello World!</h1>
        <img onload="console.log('IMG ONLOAD')" src="https://developer.cdn.mozilla.net/media/redesign/img/logo_sprite.svg?2014-01" alt="Smiley face" width="42" height="42" />

      <script>
        document.addEventListener("DOMContentLoaded", function() {
          console.log("END - DOMContentLoaded");
        });
        document.addEventListener("load", function() {
          console.log("END - document load");
        });
        window.addEventListener("load", function() {
          console.log("END - window load");
        });
      </script>      
    </body>
</html>

would result in

  • "Head - DOMContentLoaded"
  • "END - DOMContentLoaded"
  • "IMG ONLOAD"
  • "head - window load"
  • "BODY ONLOAD"
  • "END - window load"

JSBin

And not all browsers support document.load.

Upvotes: 4

Related Questions