Async vs Defer* the most confusing topic. A lot of programmer want understand this.
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)
- first of all HTML parsing
- script fetching comes in picture
- after script is fetched, script executes
There are 3 cases of running scripts :
- Normal script :
<script src="..." />
- first of all HTML parsing starts
- when script tag encounters HTML parsing pause and script fetching comes in picture
- after script is fetched, script executes
- at last HTML parsing continue and finished and DOM is ready
- Async attribute in script :
<script async src="..." />
- first of all HTML parsing starts
- script is fetched asynchronously with HTML parsing
- after script is fetched, HTML parsing stops script executes
at last HTML parsing continue and finished and DOM is ready
Defer attribute in script :
<script defer src="..." />
- first of all HTML parsing starts
- script is fetched asynchronously with HTML parsing
- after script is fetched, HTML parsing completes
- 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