Async vs Defer

·

2 min read

Async vs Defer* the most confusing topic. A lot of programmer want understand this.

blog.jpg

Don't worry after this blog you will never be confused about this topic.

Basically we use async and defer in script tags.

Before coming to async and defer first of all learn what happens in DOM(Document Object Model)

  1. first of all HTML parsing
  2. script fetching comes in picture
  3. after script is fetched, script executes

There are 3 cases of running scripts :

  • Normal script :
<script src="..." />
  1. first of all HTML parsing starts
  2. when script tag encounters HTML parsing pause and script fetching comes in picture
  3. after script is fetched, script executes
  4. at last HTML parsing continue and finished and DOM is ready
  • Async attribute in script :
<script async src="..." />
  1. first of all HTML parsing starts
  2. script is fetched asynchronously with HTML parsing
  3. after script is fetched, HTML parsing stops script executes
  4. at last HTML parsing continue and finished and DOM is ready

  5. Defer attribute in script :

<script defer src="..." />
  1. first of all HTML parsing starts
  2. script is fetched asynchronously with HTML parsing
  3. after script is fetched, HTML parsing completes
  4. at last script executes and DOM is ready

If it looks difficult to learn then try this table to remember this concept for long time

dw.png