My attempt at being helpful—it’s annoying I have to explain this.
There has been a mild amount of confusion regarding how Async and Defer work when including scripts. This is kind of necessary if you have rather chunky scripts, or scripts that you want only to run after the DOM has finished rendering.
Rendering is the parsing of HTML—this makes up the DOM. JS downloading is the script downloading to the browser, and JS execution is when the script is executed. This is a fairly standard timeline in all browsers, and you can visualise it using most browser’s developer tools to see what’s holding up page-load time.
Without any attributes, the browser will wait until the file has downloaded before it continues parsing the rest of the page. This means, if you have JS nested in the head of your page, it will wait for it to download and complete before it continues rendering the rest of the page.
<script async> tags
<script defer> tags
With the defer attribute, the script will download while the HTML is parsed, and will execute once that page has been completed rendered.
Where should I use async and defer?
Try and use async where possible—but just keep an eye on some issues.
- If you only have one script in the page, and it’s modular—use async.
- If a script relies on another script, use defer—unless in IE9 or earlier.
- If a script is relied upon by an async script, then use it above the async script.
- Try and avoid using defer if you’re in a pre-IE9 web application