19

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

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • Another explanation of `async` and `defer`: https://stackoverflow.com/questions/10808109/script-tag-async-defer – bajro May 31 '18 at 00:41
  • Both "async" and "defer" loading external script asynchronously. So you don't need to set them both, unless you really need "async", which has higher priority in modern browsers. Use "async" if you want to interact your script with page immediately after it will be loaded. Use "defer" if your script depends on some other script and you should use them in correct order. Eg first is jQuery (defer), following by all jQuery plugins which require jQuery. But never set "async" to jQuery, because it so will be executed in any unpredictable place/time once it will be loaded. – Aleksey Kuznetsov Aug 18 '18 at 16:29
  • https://stackoverflow.com/a/68929270/7186739 – Billu Oct 21 '21 at 18:08

1 Answers1

24

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.

Duc Filan
  • 6,769
  • 3
  • 21
  • 26
  • So will a modern browser, say Chrome, treat the script as defer or async when it encounters them both? – AngryHacker May 31 '18 at 00:53
  • 7
    `async`. To be clear, `defer` is ignored if `async` is set and the script is loaded asynchronously. If both are present and the browser only supports `defer` then it will fall back to the `defer` behavior. – Duc Filan May 31 '18 at 00:57