'async' vs 'defer' attributes in JavaScript

async and defer are Boolean attributes which are used along with script tags to load the external scripts efficiently into our webpage.

Whenever the page is loaded into the browser, there are two major things happening in the browser, one is HTML parsing and second is the loading of the scripts.

Here loading of the scripts contains two parts:

  1. Fetching the scripts from the network.

  2. Executing the scripts line by line.

Let's understand by taking three scenarios:

<!-- Scenario One -->
<script src="../"></script>

<!-- Scenario Two -->
<script async src="../"></script>

<!-- Scenario Three -->
<script defer src="../"></script>

In Scenario one, when a browser is loading a webpage, it parses the HTML line by line. Suppose it suddenly encounters a script tag, so what happens is, the browser pauses the HTML parsing at that point of time and then fetches the scripts from the network and then execute it. After the execution of the scripts, browser continues to parse the HTML from where it paused.

In Scenario two(async), meanwhile the HTML parsing is going on, any of our script with the async tag are fetched from the network asynchronously. As soon as the script parsing is finished from the network, the script execution starts and when the script execution is finished, HTML continues to parse in the browser.

async

In Scenario three(defer), while the HTML parsing is going on, the scripts are fetched from the network simultaneously. When HTML is fully parsed, then only the script execution starts.

defer

Note:

async attribute does not guarantee the order of execution of scripts but defer does.

Means, if you are putting async attribute in multiple scripts, suppose you have multiple scripts which are dependent on each other, so using async attribute it does not guarantee that these scripts will be executed in a particular order which may break your code. In that case we can use defer.

Other example is, suppose you have loaded external script in you code, let's take the example of google analytics which are quite modular and are independent of our normal code. So in that case, it make sense to use async attribute.

Otherwise it is wise to use defer attribute because defer attribute maintains the order of execution of the scripts.