2
votes

By my understanding async scripts are executed before document parsing finished and defer scripts after that. But what about their relation to the window.onload event?

If I understand correctly async scripts are guaranteed to run before window onload and deferred may execute after that. Is that right? Or are both of these kinds of scripts always executed before window onload?

2
I'm not 100% sure, but from the MDN script page it sounds more that async scripts are just queued up in the async queue and executed as soon as the engine pick them from there. I'm not sure there's any relation with the window.onload event.MarcoL

2 Answers

4
votes

MDN says the following about the load event:

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.

Async scripts are loaded as soon as they are downloaded, defered scripts are loaded after the HTML is parsed. And after they are loaded too, the load event triggers. So yes, it is guaranteed in the specs.

1
votes

Yes, async and defer scripts do run before the window's load event.

I just want to point out that the event is called load, not onload. window.onload is one way to attach an event handler for this event.

I would also recommend attaching a load event to the script element itself, rather than on the window object:

<script>
  var script = document.createElement("script");
  script.addEventListener("load", function(event) {
    console.log("Script finished loading and executing");
  });
  script.src = "http://example.com/example.js";
  script.async = true;
  document.getElementsByTagName("script")[0].parentNode.appendChild(script);
</script>