given I asynchronously(!!) load several JavaScript files with an asynchronous script loader (that writes a script tag into the document’s head that then will download the file), are these scripts evaluated in parallel?
<script>
var script = document.createElement('script');
script.src = "library1.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
<!-- Other Markup -->
<script>
var script = document.createElement('script');
script.src = "library2.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
<!-- Other Markup -->
<script>
var script = document.createElement('script');
script.src = "library3.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
“Normally”, when having a standard script tag in the HTML document (body and head!?) the browser will stop/complete all other activites (downloading/page rendering) and only process the single script tag that it encountered. This leads to a “serialized” execution that does not lead to any “race conditions”.
But by using the asynchronous loader technique, will the inserted script tag (in the head) also lead (in the end) to a serialized rendering (that when downloaded) only “the current” script will be evaluated or is there the chance that other asynchronously loaded script files will be evaluated in parallel and therefor are prone to race conditions?
Thank you very much!!
Tim
Although scripts will be downloaded in parallel, the order in which they are executed is not deterministic. IE will execute them in the order they finish downloading in, whereas Firefox executes them in the order they are attached in the DOM.
This is a problem. For example, say script A and script B are added using that technique. Now imagine script A is jQuery, and script B does this:
In IE you’re screwed if for whatever reason (eg, network traffic, cache miss) script B finishes downloading before script A, because it will be executed before jQuery has been loaded.
See this article for a better explanation.
As for a solution, you can instead place the
<script>elements as far down the page as possible (eg before the closing</body>element. Although this does not guarantee parallel downloads, it does help alleviate the “blocking” problem your solution is addressing.