9

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?

8
  • possible duplicate of Script Tag - async & defer Commented Feb 17, 2015 at 2:57
  • @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 togeather Commented Feb 17, 2015 at 3:22
  • Maybe, but it has your answer. Commented Feb 17, 2015 at 3:27
  • @AlexanderO'Mara really? I cant see it in there. jfriend00 talks about not using all async but not about if async and defer interact Commented Feb 17, 2015 at 3:37
  • Oh, I think I see. You are asking if defer will wait for async? Commented Feb 17, 2015 at 3:40

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think 'script3.js (defer) will wait for script1.js (async), script2.js(async) and '' in order to be executed.' is incorrect, I get 3 happening in the middle of the other 2 when I try your sample
defer will wait for <body>, not for async scripts. I will just update my answer
The answer seems to be no, thats a bit of a shame really.
Looks like It's a good idea mark as async only the script who nobody depends on it to be executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.