Search code examples
javascripthtmlasynchronousonloaddeferred-execution

Are external async/defer javascripts guaranteed to execute before the window onload event?


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?


Solution

  • 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.