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.

Key-1461632500393.jpg

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.

Traditional-1461632661541.jpg

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.

Async-1461632769766.jpg

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.

Defer-1461632816394.jpg

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
 
1
Kudos
 
1
Kudos

Now read this

Multi-node docker deployments with persistent storage

A trait of Docker is that it doesn’t persist state. This is usually great when working with worker applications that don’t need to store and share data, however in the case of databases or even small WordPress instances, persisting state... Continue →