ModernDesigner
ModernDesigner

Reputation: 7717

How to make sure that certain libraries are included before executing script?

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!

Upvotes: 1

Views: 101

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219946

You should pass in the tool as a string, then check the window object for that key:

var require = function( tool ) {
    if (window[tool] === undefined) {
        alert("[" + tool + "] is not defined.");
    } else {
        pass();
    }
}

require( 'jQuery' );

Here's the fiddle: http://jsfiddle.net/9vXM2/

Upvotes: 1

wmitchell
wmitchell

Reputation: 5745

http://yepnopejs.com/ is what you are after @ModernDesigner

Upvotes: 1

Related Questions