ios85
ios85

Reputation: 2134

loading a backup copy of jQuery when CDN is down

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() {
...
}

Upvotes: 7

Views: 2727

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

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>

Upvotes: 18

SLaks
SLaks

Reputation: 887365

Your fallback code loads jQuery asynchronously.
That means that the rest of your scripts run before jQuery loads.

Adding an alert() call forces the rest of your code to wait (until you click OK); by the time that happens, jQuery will have loaded.

Instead, you can emit a new <script> tag using document.write() to load it synchronously.

Alternatively, you could wrap the rest of your code in a callback and call the callback(s) after jQuery loads.
If you do it this way, you should use a script loader library, which will handle all of that for you.

Upvotes: 3

Related Questions