In javascript, I want to know if there’s a way to check if a certain library (jQuery, Modernizr, etc.) is present, and if not, throw an alert.
Something like: require( jQuery ); // if jQuery is undefined, display an alert
Or: require( Modernizr ); // if Modernizr is undefined, display an alert
I know that this is possible because Modernizr and jQuery are objects, therefore I made sense to check the typeof, like so:
function pass() { } // use as noop
var require = function( tool ) {
if(typeof(tool) == "undefined") {
alert("[" + tool + "] is not defined.");
} else {
pass();
}
}
require( jQuery );
But that doesn’t work, of course, because Chrome’s error console says "Object [jQuery] is not defined." because I tested for something that doesn’t exist. Any tips?
Plenty new to JavaScript, so any help would be much appreciated!
You should pass in the tool as a string, then check the
windowobject for that key:Here’s the fiddle: http://jsfiddle.net/9vXM2/