I came across the following piece of code:
<script src="foo.js" async defer>
I understand that <script async...>
will download the script, then parse it pausing HTML parsing. I also understand that <script defer...>
will download the script and parse after all HTML is parsed.
What does <script async defer...>
do (e.g. async and defer used together)?
Yes, you can use both attributes but you need to use defer or async, not both.
Async - means execute code when it is downloaded and do not block DOM construction during downloading process. Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.
In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is important. And async is used for independent scripts, like counters or ads. And their relative execution order does not matter.
defer. This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded . Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.
If you specify both, async
takes precedence on modern browsers, while older browsers that support defer
but not async
will fallback to defer
.
For the support table, check caniuse.com
for async and for defer.
P/s: These attributes make only sense when using the script in the head
portion of the page, and they are useless if you put the script in the body
footer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With