- HTML parsing starts
- HTML parsing pauses when a
- Finally the HTML parsing is resumed
For this reason, a common practice is to place all the
The good news is that there are some surprisingly easy-to-implement alternatives to this approach.
By placing the
async attribute in a
<script> tag, the script will be downloaded without pausing the HTML, but as soon as it finishes downloading, it runs (blocking the HTML parsing while doing so). This approach is very suitable for displaying ads in your page, e.g.
This is how you get an actual asynchronous JS loading. The
defer attribute uses a more "polite" approach towards the HTML document, as it downloads the script, but waits until the HTML parsing is done before running it.
When a pack of wolves is traveling, the older members go in the front, as they move slower, so the rest of the pack is forced to move at the pace of the older.
What does this have to do with JS loading?
The bigger advantage to using
defer is that once the HTML is parsed, the JS scripts will potentially be in a queue, ready to be executed, in the same order as they were inserted in the document. You might want to place the bigger files above the smaller ones (as they take longer to download). Also, by doing so, feel free to place your
<scripts> is the
<header> of the document, so their download will begin as early as possible!
Another interesting option is loading a script conditionally, let's say by a click of a button. You can add an
eventListener to the button, and use something like the following:
let script = document.createElement('script'); script.src = "my-script.js"; document.body.append(script);