JavaScript—async vs defer

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.

Traditional <script> tags #

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.


Attributed <script async> tags #

With the async attribute, the script will download while the HTML is parsed, and the render will pause once the download is completed to execute the JavaScript.


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

  1. If you only have one script in the page, and it’s modular—use async.
  2. If a script relies on another script, use defer—unless in IE9 or earlier.
  3. If a script is relied upon by an async script, then use it above the async script.
  4. Try and avoid using defer if you’re in a pre-IE9 web application

Now read this

Using Web Workers to run JavaScript in parallel

JavaScript, in the browser, runs in a single thread. This is fine, and works fairly well for most websites. However, when running large, complex tasks or long scripts, it makes the webpage unresponsive. The best way to speed up these... Continue →