I have some confusion around the new async attribute to the script element in HTML5 that I hope someone can give a clear answer to.
Browsers are capable of Parallel Connections, therefore images will be downloaded in parallel. But any external javascript is not downloaded in parallel with other external javascript and images. Scripts block page loading until they have been downloaded and executed.
To download a script without blocking the rest of the page loading, the most common technique is to create a script element, like Google Analytics snippet does:
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.src = '...ga.js'; ga.async = true; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
I'm not sure of how that works exactly - either
or
I think it is the latter.
The new asynchronous Google Analytics snippet includes the HTML5 async attribute in the script element it creates. That will not help the page blocking problem - that has already been solved by the "Script DOM Element" technique. So what does async add to the picture? According to w3schools, "if async is present, the script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)".
And according to Steve Souders site, "the main benefit of this [async attribute] is it tells the browser that subsequent scripts can be executed immediately – they don’t have to wait for ga.js".
So are async and the Script DOM element technique both solving the same problem?
The async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously as soon as it is available. Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).
Async allows execution of scripts asynchronously and defer allows execution only after the whole document has been parsed.
Async and defer are basically two boolean attributes for the <script> tag. Async allows the execution of scripts asynchronously as soon as they're downloaded. Defer allows execution only after the whole document has been parsed. Both attributes don't have any effect on inline scripts.
Will work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>$('body').append('Yey');</script>
Will not work:
<script async src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>$('body').append('Yey');</script>
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