These HTML attributes are said to be powerful. Let’s check it.
defer are simple attributes to use with your script tags =
It might seem self-explanatory, but I’ve seen a lot of misuses.
Do you need both? Where to use it? When to use it?
Here are very light descriptions for these attributes:
Differences with/without these attributes
As we just saw, you have to add those attributes if you want the browser to act differently. Without
defer, the browser stops parsing the document every time it finds an external js call, such as
In this case, the browser pauses its parsing and fetches the js file to execute it. That’s the reason why you often read that those calls are blocking.
In that perspective, it’s a good practice to put your js calls at the end of the document, just before the
</body> tag when it’s possible, to reduce the amount of blocking resources. Lighthouse often tells you that ^^.
async to the rescue
The best-case scenario for
async is when you need support for modern browsers only, and your script is entirely standalone, with no dependencies, so you don’t expect results from other scripts to run your code.
But I’ve seen the use of both attributes
It’s not rare to see both attributes on the same tag:
People may use that for ancient browsers where
async is not supported, so it fallbacks to
defer is pretty much older than
async ( IE 6 for
defer vs. IE 10 for
I don’t get it. Is it
defer, or both?
There are subtleties you have to know.
If your scripts are very close to the closing
</body> tag, it makes less sense to defer or async as the browser has almost finished its parsing. You won’t significantly improve performances in this case.
async, the browser fetches your script asynchronously, but with
defer, it will execute it only after parsing the whole HTML document, whereas, with
async, it will execute it as soon as your js is ready.
As a result, the browser parsing may still pause even if you use
It’s worth noting that if you defer several scripts, they will execute in the same order you’ve added them, even if it’s deferred. It’s not the same with
async. You don’t get the same level of control.
You won’t eliminate all render-blocking issues by using
async, don’t write the following:
<script src="mylib.js" async></script> <script src="myscript.js" async></script>
myscript.js needs functions set in
mylib.js, it won’t work as you might expect. Remember that as soon as the script is available, the browser executes it with
I’ve used the
async attribute in particular cases only. I prefer the
defer attribute, but I don’t use it either if my script tags are very close to the closing
Again, the vast majority of modern browsers and rendering engines are pretty good at deferring and optimizing stuff, so it’s probably more clever not to add anything than introducing nasty bugs, but these attributes are still impressive.