-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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