I want to include jQuery from CDN into my code. I also want to create a fallback. My original solution was to check if CDN has failed, and if so use document.write
to insert the fallback <script>
into the DOM
.
Now Google is saying not to use document.write
so instead I have changed my fallback function to dynamically insert the local <script>
path into the DOM
:
<script>
function fallback(id, localScript) {
fallBackNode = document.getElementById(id);
// insert local jQuery path, right after fallback (does not work)
fallBackNode.insertAdjacentHTML("afterend", "<script src='" + localScript + "'><\/script>");
// insert local jQuery path, (works)
//document.write('<script src="' + localPath + '"><\/script>');
}
</script>
// jQuery CDN
<script src="https://code.jquery.com/jquery-3.6.0.9-INVALID_CDN.min.js"></script>
// jQuery fallback
<script id="jqueryfallback">window.jQuery || fallback('jqueryfallback', '/Scripts/jquery-3.6.0.min.js');
// jQuery ui CDN
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script></script>
Both of the above options (i.e. using document.write
and using fallBackNode.insertAdjacentHTML
) produce exactly the same result, they insert my local path right after the fallback check, as shown below:
<script id="jqueryfallback">window.jQuery || fallback('jqueryfallback', '/Scripts/jquery-3.6.0.min.js');</script>
<script src="/Scripts/jquery-3.6.0.min.js"></script> // <-- both solutions insert this line here
However when I use document.write
everything works fine and the local jQuery gets loaded before jQuery.ui... but if I use the fallBackNode.insertAdjacentHTML
option, I get the following error in jQuery.ui:
It seems like, jQuery.ui which is the next library, does not wait for the local jQuery to be inserted into DOM, and throws error... how can I resolve this issue?