Javascript: Difference between async and defer in the script tagJavascript
If you do a Google search on how you’d like to include the script tag asynchronously, you’re bound to come across the keywords async and defer. And while both attributes are used to load scripts asynchronously, there are some fundamental differences between them that we’ll explore together and help you make your decision.
Let’s start with async 😊
When you want to load a script asynchronously while continuing to parse and display the rest of the page, the “async” attribute is the ideal candaidat. Thanks to this keyword, your script will be downloaded in parallel with other resources, and its execution will start as soon as it’s available, even if the rest of the page hasn’t finished loading. To use it, just add async to your.
<script async src="app.js"></script>
What about defer? 🤔
The defer attribute is also used to load scripts asynchronously, but with one key difference. Scripts with the “defer” attribute will be downloaded in parallel with other resources, but will only be executed once the HTML page has been parsed.
<script defer src="app.js"></script>
Which one to choose?
To help us decide, let’s look at the pros and cons of both.
async: advantages and disadvantages
As for the advantages of the async attribute, we can note an improvement in page loading performance, as it is not blocked by rendering. It is therefore useful for scripts that do not depend on a precise order of execution.
However, async is not ideal when there is a dependency on other scripts or when the execution order of scripts is important.
defer: advantages and disadvantages
The strong point of the defer attribute is when there’s a need for scripts to be executed in a specific location, or when scripts depend on each other.
However, it is not ideal for critical scripts that need to be executed immediately. In addition, with defer, there may be a slight delay in script execution, since the script has to wait until the HTML is completely parsed.
What to remember 🤔
The appropriate use of the “async” and “defer” attributes in the script tag depends on the specific needs of your page and your JavaScript scripts. If you want to execute your scripts immediately, use async; otherwise, use defer.
Happy coding 👨💻