Rendering DOM or Webpage faster is one of challenging task that every developer face🤯. One of the main factors of the slow rendering of DOM is the strategy with which we load the JavaScript because JS blocks the parsing of HTML and that’s why the DOM performance highly depends on it.
However, few keywords can be used with script
tag to boost the performance. The <script>
tag has two attributes that do the magic⚡️ for us : async
and defer
.
Here’s what we’ll cover in this article:
-
<script>
without attributes. -
<script>
async attributes. -
<script>
defer attributes.
So let’s dive in!
<script>
without attributes
As soon as the browser encounters the script
tag, the HTML parsing is blocked and will only start up again after the JavaScript is fetched from the server and executed.
While the Javascript is loading, the building up of the DOM is paused and that reduces the performance and increases the loading time of the webpage.
<script>
async attributes
Using async
attribute downloads the script files asynchronously during HTML parsing ( in the background). After it finished downloading, only then it paused the HTML parsing and start executing the script file but before the window’s load
event.
The async
attribute does not guarantee the order of execution of script files. The script files will be executed asynchronously or in random order.
<script>
defer attributes
The defer
attribute also downloads the script file during HTML parsing( in the background) but will only execute it after the HTML parsing is completed but before DOMContentLoaded event.
Using defer
in the script tag also assured that the scripts will be executed in the same order as they appear in the file. This is very much useful in the scenario when one script depends on another script.
This is how it all works: 👇
Similarity
Both defer and async attribute downloads the script in background while the HTML parsing is going on. Downloading of scripts this way does not block the rendering of DOM and as a result, user can see the webpage instead of a white screen.
Difference
defer
:- Script execution starts after HTML parsing is finished but before the DOMContentLoaded
event.
async
:- Scripts execute after they finish downloading but before the window’s load
event.
Where async and defer use?
- If the script files are dependent on each other, then use
defer
attribute. -
async
attribute is useful when we don’t care when the script loads and scripts do not rely on each other. -
defer
maintains the order of execution of script butasync
doesn't.
Conclusion
Congratulations for reading until the end! In this article you’ve learned:
- Javascript async and defer
- Similarity and difference and where to use of async and defer attributes in script tag.
Top comments (0)