Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "async defer" do when used together? [duplicate]

Tags:

javascript

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)?

like image 421
AngryHacker Avatar asked May 31 '18 00:05

AngryHacker


People also ask

Can async and defer be used together?

Yes, you can use both attributes but you need to use defer or async, not both.

What does async defer do?

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.

When would you use async defer?

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.

What does defer do in script tag?

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.


1 Answers

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.

like image 59
Duc Filan Avatar answered Sep 28 '22 02:09

Duc Filan