Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
...
}
like image 747
ios85 Avatar asked Dec 06 '12 15:12

ios85


2 Answers

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>
like image 65
Blazemonger Avatar answered Nov 05 '22 00:11

Blazemonger


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.

like image 24
SLaks Avatar answered Nov 04 '22 22:11

SLaks