Scripts Execution Order

Prompt
What would be the order of execution of the scripts?
<script async src="async1.js"/> // 300ms
<script defer src="defer1.js"/> // 200ms
<script defer src="defer2.js"/> // 300ms
<script async src="async2.js"/> // 50ms
<script async defer src="asyncdefer1.js"/> // 60ms
Remember that async
scripts get executed as soon as they are downloaded and defer
scripts get executed after the HTML parser has finished parsing.
Solution
The correct order of execution is:
<script async src="async2.js"/> // Loaded in 50ms
<script async defer src="asyncdefer1.js"/> // Loaded in 60ms
<script async src="async1.js"/> // Loaded in 300ms
<script defer src="defer1.js"/> // Loaded in 200ms
<script defer src="defer2.js"/> // Loaded in 300ms
A regular script which does not have the async
or defer
attribute will block the DOM from being parsed until the script is loaded. This is called render-blocking. In this case the HTML parser has to stop, fetch the script, execute it, and then continue parsing the DOM.
By using async
attribute, when the script tag is discovered by the HTML parser, it still fetches the script but in the meantime the parser continues to parse the HTML. But, when once the script is downloaded, it will block the HTML parser and the script will get executed on the main thread, once the execution of script is finished, the parser will continue to parse the HTML.
By using defer
attribute, when the script tag is discovered by the HTML parser, it fetches the script asynchronously and does not execeute when the script is downloaded. Instead, the script is "deferred" and will be executed after the HTML parser has finished parsing.
In case of async
scripts there is no guarantee that the script will be executed in the order of the script tags. It gets executed as soon as it is downloaded.
In case of defer
scripts the script will be executed in the order of the script tags.