TIL about the behavior of script loading in an HTML page, when the
async attribute is added to a script tag.
What is the
async attribute allows a script to be downloaded and executed asynchronously from a non-inline script source (adding
async to an inline script does not affect behavior of its execution).
These scripts will load asynchronously, and will not block the parser while they download.
So we should use this all the time, right?
Not so fast… there are some considerations you’ll need to make before adding
async attributes to all of your script tags.
The order of execution of scripts with the
async attribute is no longer guaranteed by the script’s position in the document. In other words, in the above example it is not guaranteed that a.js will execute before b.js. This can be problematic if, for example, a.js is a library that b.js depends on to execute.
Another consideration, is if the scripts you are asynchronously loading depend on HTML elements of the document being parsed and added to the DOM before the scripts execute.
For example, let’s say script tags with the
If your script meets the following criteria, then feel free to add the
async attribute and move script tags to the head of the document:
- The script does not depend on particular DOM nodes to be present to successfully execute.
- The script does not depend on the instantiation of variables or objects from other scripts to successfully execute.
Otherwise, it is still safest to just load your scripts synchronously at the bottom of your HTML page.
With this in mind, the recommendation for script loading above still stands, and the argument for using the
async attribute while loading scripts becomes even less necessary (in my opinion).