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?
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.
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