Hello guys, In today's blog let us discuss what async and defer attributes are and why should we use them.
Before we dive deep into understanding these attributes, let's first take a quick look on how the <script>
tag works, and how scripts are fetched and executed without the above two attributes.
The Script tag
<script src="./index.js"></script>
HTML <script>
tags are used include executable code (often Javascript code). The src attribute can be used to embed external JavaScript code.
Script tag without Async and Defer attributes.
With reference to the above image, Imagine an HTML page having a <script>
tag with an src
attribute.
Firstly the Parser starts parsing the HTML and as soon as the script
tag is encountered by the parser the HTML parsing is paused and it starts fetching the script. After all of the script is fetched, then it starts executing it, and after the execution of the script is finished then the HTML parsing is finally resumed.
This phenomenon is called parser-blocking, and the script is called parser-blocking JavaScript where HTML parsing is paused for a period of time, which can result in half-loaded pages or very slow loading.
Why HTML parsing is paused?
It might be possible that the script may contain method calls likedocument.write()
that fundamentally changes how the subsequent markup should be parsed.
Eliminating Parser-Blocking-script
We will now see how async
and defer
attributes help us to eliminate the parser blocking behavior. Both of these are boolean attributes.
Boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
Async
<script async src="./index.js" ></script>
As shown in the image above, if the script tag contains the async attribute, then the HTML parsing does not pause, but instead, the script is fetched asynchronously (parallel). Only when the script is fetched, the HTML parsing is paused, and after the script's execution is finished, the HTML parsing is resumed again.
Defer
<script defer src="./index.js"></script>
if the script tag contains the defer attribute, then the HTML parsing is never paused. The script is fetched asynchronously (parallelly) and is executed only after the HTML is completely parsed.
When to use what
async
attribute doesn't guarantee the order of execution of scripts, while scripts with the defer
attribute are executed in the order in which they were called.
Hence if there are multiple scripts that are dependent on each other then defer
should be attribute.
Conclusion:
That was all about Async and Defer boolean attributes. If you've reached this point, Thanks for taking your time and reading this article, hope you've enjoyed reading it and found it helpful. Do not hesitate to share your feedback.
Lets connect ๐ค๐ป