defer attributes to the script tag?
In this article, we'll take a look and understand major differences between async and defer attributes and which one is better to use. But first, let's understand what if we don't use them at all.
<script> tag without async or defer
Let's take a look at the following code.
When the browser runs this file it starts by parsing the HTML line by line. In this example, as soon as the browser sees the
This is not a good thing because if you are working on a large project then even a delay of say 1 second might lead people to go back from your website and eventually hurt the revenue.
We can solve this by using
defer so let's take a look at them.
When we use the
defer attribute is quite similar to
async. The one difference is that the scripts loaded with
If multiple scripts are being used in HTML file and some are dependent on others, so in order for them to work correctly, we need to make sure that the script on which others are dependent are loaded and executed first in the browsers before the script which is dependent on this script.
Let's take an example,
<script async src="script-1"></script> <script async src="script-depended-on-script-1"></script> <script async src="script-depended-on-script-above-this"></script>
If we use
async in this case then it does not guarantee that
script-1 will be loaded and executed before the
script-depended-on-script-1 because these scripts are being fetched in the background and one might be fetched before the others due to any reason, like its size or network issue. So if
script-depended-on-script-1 is fetched first then it will be executed first because when using
deferhowever guarantees that scripts will be executed in the order even if one is available to the browser before the other because all scripts will be executed after the HTML parsing is done.
- If you have multiple scripts that are dependent on each other then use
deferas it guarantees the order of execution.
- If you don't want to block the HTML parsing then use
- I personally recommend using
defermost of the time.
I hope you found this interesting and learned something. Thank you.
Per Aspera Ad Astra
Top comments (2)