Reputation: 1704
I'm trying to write a simple dependency loader, and I'm having trouble while testing against the libraries to see if the initial load was successful or not. The primary hurdle seems to be due to my storing of the var name for each library as a string.
var libraries = [
{
libvar: 'jQuery',
cdn: '//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js',
fileName: 'jquery-2.1.4.min'
}, {
libvar: '_', // Underscore.js
cdn: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js',
fileName: 'underscore-1.8.3.min'
}
];
var checkLoad = function(library) {
if (!library || !library.fileName.length) return;
document.addEventListener('DOMContentLoaded', function() {
var thisLib = eval(library.libvar);
if (!thisLib) {
script = document.createElement('script');
script.setAttribute('src', 'js/fallback/' + library.fileName + '.js');
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script);
console.warn(library.libvar + ' loaded via fallback', thisLib); // Testing
} else {
console.warn(library.libvar + ' is loaded!'); // Testing
}
});
};
for (var i = 0; libraries.length > i; i++) {
document.write(unescape("%3Cscript src='" + libraries[i].cdn + "' type='text/javascript'%3E%3C/script%3E"));
checkLoad(libraries[i]);
}
The error i'm getting is:
Uncaught ReferenceError: jQuery is not defined
... where "jQuery" is simply the name of eval(library.libvar) for the link that I've manually broken.
The initial load and test works fine IF the script was loaded successfully from the cdn. But if I manually break cdn link, the script is suppose to attempt the fallback but instead is throwing a js error and halting.
I'm struggling to figure out how to write an appropriate test that will fail correctly without thowing an error and halting everything.
Per dbrin's solution, the fixed DOMContentLoaded function looks this:
document.addEventListener('DOMContentLoaded', function() {
if (!window[library.libvar]) {
var script = document.createElement('script');
script.setAttribute('src', 'js/fallback/' + library.fileName + '.js');
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script);
}
});
Upvotes: 0
Views: 2178
Reputation: 15673
Here is an example:
if(window['jQuery']) {
// Hooray jQuery is loaded!
}
Upvotes: 3
Reputation: 3859
Noting how (in general) the library root objects become properties of the global window
object, I would suggest you do something like:
var thisLib = eval("window." + library.libvar);
That way the if checks shouldn't fail.
Upvotes: 0