async/defer attributes and DOM construction

5. DOM injection (async false)

Result

Hello World!

Markup

<script>
function load(src, async) {
    var js = document.createElement('script');
    js.type = 'text/javascript';
    js.async = async;
    js.src = src;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(js, s);
}
</script>
<p id="result">
    Hello
    <script>load("A.js", false);</script>
    <script>load("B.js", false);</script>
    <script>load("C.js", false);</script>
    World!
</p>

DOM elements and Events

Description

Major HTML5-compliant browsers (IE10+, latest Gecko and WebKit) implement keeping the order of execution when async attribute is set to false in case of DOM injection method (or script-inserted external script). Note: Setting defer attribute to true has no effect because it’s for parser-inserted script by means of WHATWG recommendation.

On the other hand, HTML5-noncompliant browsers such as IE9-, pre-4.0 Firefox and pre-18 Opera does not keep the order of script execution even in case of using DOM injection method.

Therefore at this moment, you should not use this browser dependent method. You can use cross-browser script loader such as LAB.js, Require.js or $script.js, if you wish asynchronous loading and controlling the execution order.

You can see a similar demo at HTML5 Async Scripts on Microsoft IE Test Drive.

References