How does the use of async and defer differ when considering the script execution after download and its impact on page performance?
Async
- Blocks the parsing of the page when executed
- Executed as soon as it is available
Defer
- Executes after the page has finished parsing
- Executes before the
DOMContentLoadedevent - Respects scripts order
To 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?
Your next paragraph explains it at best. I didn't even know that async can block. So nice research :)
Yes. Look at the spec:
https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#attr-script-async
@ty at https://stackoverflow.com/a/13821238/7387397
Depends on the script. If its an Analytics script, I personally prefer
asnycbecause 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
deferand 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 :)