undefined
undefined

Reputation: 34269

HTML5 script tags, does defer wait on any previous async scripts

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?

Upvotes: 9

Views: 1871

Answers (1)

nanndoj
nanndoj

Reputation: 6770

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

Upvotes: 1

Related Questions