How does the use of async
and defer
differ when considering the script execution after download and its impact on page performance?
Async
Defer
DOMContentLoaded
eventTo me it seems that defer
would have a lower impact, since the execution after download happens after page parsing, while async
script execution after download blocks the parsing. But why then I see so often the use of async
and defer
together, where the later is just a fallback? Async seems just to be the modern way to go but I do not get why. If both async
and defer
work for my case, wouldn’t defer
have lower performance impact? Or is the fact of executing scripts asynchronously a win over deferring, even if the async
blocks parsing?
How does the use of async and defer differ when considering the script execution after download and its impact on page performance?
Your next paragraph explains it at best. I didn't even know that async can block. So nice research :)
But why then I see so often the use of async and defer together, where the later is just a fallback?
Yes. Look at the spec:
https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.
@ty at https://stackoverflow.com/a/13821238/7387397
If both async and defer work for my case, wouldn’t defer have lower performance impact? Or is the fact of executing scripts asynchronously a win over deferring, even if the async blocks parsing?
Depends on the script. If its an Analytics script, I personally prefer asnyc
because you get better statistics over the website. It also not depens on the DOM.
When it is a chat script or similar. I will choose if the chat is more needed then my main script. If your website works mostly without javascript you can give a "faster" TTI. Just keep in mind that Time to Interactive (TTI) can depend can also be negative for you, when you have a lot of javascripts.
Ads and other scripts can load with defer
and don't need the immediately execution.
Keep In mind, this is personally experience. It really mostly depends on the script and your website. For Performance there is no golden rule :)