Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
Not loved Avatar asked Feb 17 '15 02:02

Not loved


People also ask

Should you use defer in script tag?

You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.

Can async and defer be used together?

Yes, you can use both attributes but you need to use defer or async, not both.

What's the difference between async and defer in script tag?

Async - means execute code when it is downloaded and do not block DOM construction during downloading process. Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.

Is defer better than async?

In practice, defer is used for scripts that need the whole DOM and/or their relative execution order is important. And async is used for independent scripts, like counters or ads. And their relative execution order does not matter.


1 Answers

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

like image 178
nanndoj Avatar answered Sep 22 '22 13:09

nanndoj