Do you know the importance of defer
and async
attributes in the script tag?
When we load any webpage in the browser, the browser generates a DOM(Document Object Model) by parsing the document.
When there is no attribute(defer
or async
) to the script tag like this:
<script src="index.js"></script>
<script src="script.js"></script>
then all the scripts are downloaded and executed one after the other simultaneously.
So it will block the parsing of the document until all the scripts are downloaded and executed and therefore it will take some time to load the page completely.
Therefore it's a common practice to add all the scripts before the end of the body tag so the browser will generate the DOM first and then all the scripts will be executed like this:
<body>
.
.
.
<script src="index.js"></script>
<script src="script.js"></script>
</body>
Using defer and async
When we add the defer
attribute to the script tag, the browser will download all the scripts included in the page but will not execute it until the DOM is created.
So we can place all the scripts in the head tag with defer
attribute and is an alternative option rather than placing all the scripts before the end of the body tag.
Scripts with defer
added will execute in order.
The async
attribute works the same as the default behaviour of script tag when there is no defer
or async
attribute specified like this:
<script src="index.js"></script>
This means it will stop the parsing of the document until all the scripts are downloaded and executed.
But the difference between async
and defer
is that async
scripts will not execute in order so If we have 4 scripts included, any script will be executed at any time but that's not the case with defer
.
So when the scripts are not dependent on each other we should use the async
attribute.
Knowing when to use defer
and async
is important because even if you have not used it, it is a famous question in an interview.
Conclusion
-
async
ordefer
attributes can be added to the script tag depending on the requirement - adding
defer
attribute will make sure that all the scripts are downloaded but will not be executed until the DOM is ready - adding
async
attribute is preferred when the scripts included in the page are not dependent on each other
Due to many requests for the discount, the Christmas sale of 30% off for Mastering Modern JavaScript book is extended till 31st December. So don't miss this last opportunity.
Check out the preview contents of the book here.