loading a backup copy of jQuery when CDN is down

cdn, javascript, jquery

Solution

This is the technique used by HTML5 Boilerplate. First it loads the Google CDN script, then immediately checks if the global `jQuery` object exists -- if it doesn't, the CDN failed and a local copy is loaded instead.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.3.min.js"><\/script>')</script>

Problem

I have this code in a script we use for initializing all of our applications, it loads the jQuery from the google CDN amongst several other things that all of our applications require. Then when we load the specific program functionality we check to make sure that jquery has loaded, in case the CDN is down. The problem I am running into is it is still loading the second one. If I add a simple `alert("Test");` after the line `headTag.appendChild(jqTag);` it works perfectly, but if I remove the alert it uses the second one. What gives? They are loaded like so: ``` <script type="text/javascript" src="i-initializer.js"></script> <script type="text/javascript" src="i-program.js"></script> ``` initializer script: ``` if(typeof jQuery=='undefined'){ var headTag = document.getElementsByTagName("head")[0]; var jqTag = document.createElement('script'); jqTag.type = 'text/javascript'; jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'; headTag.appendChild(jqTag); } ``` Then in another script we have the following: ``` if(typeof jQuery=='undefined'){ var header = document.getElementsByTagName("head")[0]; var qtag = document.createElement('script'); qtag.type = 'text/javascript'; qtag.src = 'http://feedback.oursite.com/scripts/jquery-1.8.3.min.js'; qtag.onload = checkjQueryUI; header.appendChild(qtag); } else { jQCode(); } jQCode() { ... } ```

Original source