Async vs Defer attribute

Async vs Defer attribute

·

3 min read


I'm back after a 20 days without any blogs. Will be posting about what I did in these 20 days. So here's my new post about async vs defer attribute in JavaScript. Let's go.

When you load a webpage then there are two major things happening in your browsers:

  • HTML Parsing
  • Loading of the scripts

Loading of the scripts contain two parts:

  • Fetching the script from the network.
  • Executing the script line by line.

The <script> element has two attributes, async and defer, that can give us more control over how and when external; files are fetched and executed.

async and defer are boolean attributes that are used along with the <script> tag to load the external scripts efficiently into your webpage.


Normal <script> tag

<html>
 <head>...</head>
 <body>
   ...
   <script src="main.js">
   ...
 </body>
</html>

Suppose your browser is parsing the HTML and then it encounters the <script> tag.


Normal <script> tag

In the case of the normal <script> tag following steps takes place:

  • JS blocks the parsing of HTML
  • Fetches the script from the network
  • Executes the script
  • HTML parsing is started only after the script is fully executed

The async attribute

The async attribute is used to indicate to the browser that the script file can be executed asynchronously.

<script async src="main.js">

  • While using the async attribute, meanwhile, the HTML parsing is going on, any of the script with the async attribute is fetched from the network asynchronously along with the HTML parsing.

The async attribute

As soon as scripts are fetched and available in the network, HTML parsing stops and scripts start executing.

Once the scripts are executed, the HTML parsing continues like regular.


The defer attribute

<script defer src="script.js">

The defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed.

The defer attribute

In this case:

  • HTML parsing goes on and scripts are fetched in parallel
  • Scripts are only executed once the HTML parsing is complete.

This blog was originally posted at => [rahulism.tech/article/async-vs-defer-in-JS/]


😎Thanks For Reading | Happy Coding😃

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!