About async and defer of external javascripts. What if we use them both (whether it’s worth)? And how they’re actually loading in what order
Author:

Questions:

  • How scripts with async and defer attributes will be loaded and in which order?
  • What if we use both async and defer attribute for external JavaScripts? 

Answers:

Both “async” and “defer” loading external script asynchronously.

So you don't need to set both atributes, unless you really need exactly "async", but still want to make it compatible with legacy browsers. In modern browsers, if you use both async+defer, “async” has higher priority and “defer” is ignored.

You should prefer “async” if you want to interact your script with page immediately after script will be loaded, no matter before or after the page will be loaded.

Use “defer” for the scripts which depends on each other, which should be loaded and executed in some certain strict order.

For example, if you use jQuery and some jQuery plugins, you should put jQuery to the top of your scripts list with “defer” attribute + all other scripts which requires jQuery — after the jQuery, with “defer” attributes too.

But never set “async” to the scripts, if you're using some other other external scripts which depends on it. Because of “async” directive it will be executed in any unpredictable place/time once it will be loaded + “defer” will be ignored.

And again, both “async” and “defer” loading external script asynchronously, without blocking of the page content.

BTW.

  1. Google use both async and defer for some its scripts. Proof.
  2. If you want to play and test how scripts will be loaded on your page, use onload="" event of the <script> tag to display in console the order in which they are loading:
    <script scr="//domain/location/script.js" async defer onload="console.log('Loaded somescript.js with async+defer attributes')">

Send by E-mailSend by E-mail   Print versionPrint version
Comments(0)

No comments yet… Be the first to leave comment on this topic!

or
Also you may sign in using:
Enter with Facebook Enter with VK