Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically inserted script tag is not executed in the correct order

Following is a snippet of my html code:

...

<script src=".../jquery.min.js"></script>

<script id="foo">
    if (!window.jQuery) {
        var jquery = document.createElement("script");
        jquery.src = ".../jquery.min.js";
        var self = document.getElementById("foo");
        self.parentNode.insertBefore(jquery, self.nextSibling);
        console.log("haha");
    }
</script>

<script>
    console.log("hehe");
</script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

The first script tag is a jquery CDN. The purpose of the script tag with id "foo" is that in case the CDN fails, it loads a local copy of jquery file before the following bootstrap js file is loaded.

However, somehow the inserted jquery file is not executed before the bootstrap js file. I tried putting console.log("wow") in that local jquery file. The result in console is "haha", "hehe", some error message from bootstrap js file, "wow". Observing the DOM, the inserted jquery tag does appear before the "hehe" script, I am wondering why it's not executed in the right order and if there is a better way to achieve my goal?

like image 352
Xufeng Avatar asked Feb 10 '23 01:02

Xufeng


1 Answers

Dynamically inserted script files that are inserted with anything other than document.write() are not executed in ANY predictable order. They are async and will load and run at their own pace.

You cannot depend upon any load order of async scripts relative to other scripts unless you write code to monitor when things have finished loading and only run code when some specific conditions have been met.

If you insert the script with document.write(), then it will become a blocking script load and it will load and run before any script tags parsed after the document.write() statement, the same as if the <script> tag was in the source of the page in that spot. But, using document.write() potentially messes with some browser loading optimizations so there can be some downsides to using that technique.

You can use document.write() in this way:

<script src=".../jquery.min.js"></script>

<script>
    if (!window.jQuery) {
        document.write('<scr' + 'ipt src="../jquery.min.js"></scr' + 'ipt>');
    }
</script>

A whole article on this topic: CDNs fail, but your scripts don't have to - fallback from CDN to local jQuery.

like image 71
jfriend00 Avatar answered Feb 11 '23 14:02

jfriend00