9
votes

The HTML5 script tag loading directives seem pretty cool https://stackoverflow.com/a/24070373/1070291

Is it possible to async load a bunch of scripts but have a single script wait to execute based on the async ones completing.

<script src="//some.cdn/jquery.js" async></script>
<script src="//some.cdn/underscore.js" async></script>
<script src="/my-app-which-uses-_-and-jquery.js" defer></script>

Is my app script guaranteed to execute after my libraries or will it only execute in order with other defer scripts?

1
possible duplicate of Script Tag - async & deferAlexander O'Mara
@AlexanderO'Mara I think this is a different question, the one linked is more about the general behaviour of async/defer this question is about the interactions between the two when used togeatherNot loved
Maybe, but it has your answer.Alexander O'Mara
@AlexanderO'Mara really? I cant see it in there. jfriend00 talks about not using all async but not about if async and defer interactNot loved
Oh, I think I see. You are asking if defer will wait for async?Alexander O'Mara

1 Answers

1
votes

When defer present, it specifies that the script is executed when the page has finished parsing. It doesn't include async scripts.

If I have the following situation which all scripts will log the date when it was executed:

   <head>
       <link rel="stylesheet" href="style.css">
       <script src="script.js" async></script>
       <script src="script2.js" async></script>
       <script src="script3.js" defer></script>
   </head>
   <body>
     <script>
        console.log("Body script executed at : " + new Date());
     </script>
   </body>

I may have this output:

  Body script executed at : Tue Feb 17 2015 00:05:08 GMT-0300
  script2.js:2 Script 2 executed at :Tue Feb 17 2015 00:05:08 GMT-0300
  script.js:2 Script 1 executed at:Tue Feb 17 2015 00:05:08 GMT-0300
  script3.js:2 Script 3 executed at :Tue Feb 17 2015 00:05:08 GMT-0300

script3.js (defer) will wait for '<body>', but not for script1.js (async), script2.js(async).

Here is a PLUNKER