Can you use both the async and defer attributes on a HTML tag?
Yes, you can use both async
and defer
on a script tag 😲 but it's not practical, because async
will run over defer
. Here’s how it goes:
To allow execution only after HTML parsing, wave the defer
flag:
Let’s delve into more about how and when to use these attributes.
Async vs Defer: The performance battleground
There's a chess match happening in your HTML document, and async
and defer
are the strategic moves to win the performance game in script loading.
Behaviours behind async & defer
The async
attribute is like the knight of the chessboard moving independently, enabling the script to be downloaded while the HTML parsing continues and thereby ensuring a swift play.
On the other hand, the defer
attribute behaves like the bishop waiting for the right moment to attack, delaying script execution until after the HTML document is parsed.
Bringing backward compatibility in the game
While async
didn't make the cut until IE10, defer
has been a faithful comrade since IE 5.5. Hence, if you have concerns regarding legacy browser support, defer
has got your back.
Knowing the moves : execution sequence
Scripts with defer
respect their ordering in the execution, while async
scripts move as if they have a mind of their own on the board. Therefore, async
might not be helpful for your script if its execution relies heavily on other scripts' loading order.
Twisting the game : combining async and defer
Having async
and defer
together is like planning to play both the knight's move and the bishop's move. It doesn't really work that way – async
takes precedence, while defer
gracefully steps down.
Mastering the moves : script loading strategies
To level up and optimize your performance game, consider merging scripts, and be mindful of their dependencies and effects on load time. All these considerations lead to better choices between async
or defer
.
The Coding Cookbook: Recipes with async and defer
When async is your secret ingredient
Use async
for non-interactive scripts such as analytics or advertisements, which can load independently even before the full parsing of the HTML document is done.
Loving the lingering flavors with defer
Consider using defer
for scripts heavily relying on the DOM or other scripts. Using defer
assures respective execution even in older browsers that don't digest async
well.
Potential recipe disasters
It's necessary to consider potential risks when using async
and defer
:
- DOM readiness:
async
can cause our cooking timers to go off sooner than desired, resulting in a DOM that’s not fully prepared. - Script interdependencies: For interdependent JavaScript ingredients,
defer
ensures that their incorporation into the dish happens in the correct order unlikeasync
. - Trade-offs with performance: Your dish might be ready faster with
async
, but the order of the served courses might vary leaving your guests (users) with an unexpected sequence.
Was this article helpful?