Skip to content

Instantly share code, notes, and snippets.

@mondaychen
Forked from getify/gist:670840
Created January 12, 2012 03:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mondaychen/1598350 to your computer and use it in GitHub Desktop.
Save mondaychen/1598350 to your computer and use it in GitHub Desktop.
using LABjs to load from a CDN, with simple error detection (& timeout), and a local load fallback
function loadOrFallback(scripts,idx) {
var successfully_loaded = false;
function testAndFallback() {
clearTimeout(fallback_timeout);
if (successfully_loaded) return; // already loaded successfully, so just bail
try {
scripts.tester();
successfully_loaded = true; // won't execute if the previous "test" fails
scripts.success();
// console.log("success: " + scripts.src[idx]);
} catch(err) {
if ( idx < scripts.src.length-1 ) {
loadOrFallback(scripts,idx+1);
}
else if( scripts.loopRetry-- ){
loadOrFallback(scripts,0);
}
}
}
if (idx == null) idx = 0;
$LAB.script(scripts.src[idx]).wait(testAndFallback);
var fallback_timeout = setTimeout(testAndFallback, scripts.timeout);
}
loadOrFallback({
src: [ "http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js",
"http://lib.sinaapp.com/js/jquery/1.5.1/jquery.min.js",
"./js/jquery.min.js" ],
tester: function() { jQuery(""); },
success: function() {
$LAB
.script('./js/plugins/jquery.select.js')
.script('./js/plugins/jquery.nav.js')
.script('./js/plugins/jquery.tips.js').wait();
},
timeout: 1000 // only wait 1 second
loopRetry: 2
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment