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?
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.
Yes, you can use both attributes but you need to use defer or async, not both.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With