Script: Async vs Defer

Subscribe to my newsletter and never miss my upcoming articles

Hello Peeps! I am Plxity and today I am going to explain about the TWO attributes which we can use in the script tag inside our HTML file to make the rendering easier.

As we all know, we always write <script> tag at the bottom of the HTML file so that it can see the elements above and it doesn't block the page content from showing. But apparently this is not a good practice if we have long HTML documents, there can be a delay in loading. It might take time to parse the HTML elements.

There are two methods to fix this.

  1. Async
  2. Defer

Let's see each attributes one by one.

defer

This attribute downloads the file during HTML parsing and executes it after it is parsed completely. It starts loading the <script> in the background.

For example:-

<h1>Content above script tag</h1>

<script defer src="some random link to script file"></script>

<h1>Content below script tag</h1>

In this case, the content will show up immediately and the script will be loaded in the background without blocking the page. The script will be executed once the HTML is parsed completely.

Note: defer attribute works only if src is provided in the script tag i.e only for the external scripts.

If we have multiple <script> tag with defer attribute. scripts will be executed in the relative order.

For example:-

<script defer src="script1.js"></script>
<script defer src="script2.js"></script>

scrtipt1.js will be executed before script2.js

It might happen script2.js is downloaded first but will be executed always after script1.js

async

This attributes downloads the file during HTML parsing and will pause the HTML parser it to execute the downloaded script file. Same like defer this attribute does not block the loading of the page content.

This attribute means the script is completely independent i.e other scripts don’t wait for async scripts, and async scripts don’t wait for them. It can be executed in any fashion/order. Whichever script loads first will be executed.

For example:-


<script async src="script1.js"></script>
<script async src="script2.js"></script>

In this case, if script2.js is loaded first it will be executed. It won't wait for script1.js

Similarities between async and defer

The only similarity between these two is that the rendering of page content is not blocked while fetching the script.

Difference between async and defer

In defer the scripts are executed in relative order while in async whichever script is loaded first will be executed.

In defer the scripts are executed once the document is parsed and in async it is executed as soon as the script is loaded. It does not wait for the document to parse completely.

No Comments Yet