Tuesday, March 24, 2009

Check if jQuery.js is loaded

This is the very basics of any programming language, checking if some class, method, variable or property does already exist. In our case the programming environment is JavaScript and the object we are checking for existence is jQuery() / $() function.

This method is not limited to jQuery only, you can check for any other variable or function in your javascript.

Anyway, jQuery() or $() functions will only be defined if they are already loaded into the current document. So to test if jQuery is loaded we can use 2 methods.

Method 1:

if (jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded  
} else {
    // jQuery is loaded
}

NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

You can also check if particular jQuery plugin is loaded or not.


4 comments:

Michael Gaigg said...

Hey Uzbekjon, enjoying your blog tremendously. Learn something new every week.

I guess you got Method 2 mixed up. Testing for undefined results in 'not loaded' when equals.

Cheers, Mike

CTAPbIu_MABP said...

second method is reversed :)

Uzbekjon said...

@Michael Gaigg, @CTAPbIu_MABP

Thanks for the heads up guys... :)

@Michael Gaigg, It is nice to hear that people follow my posts. thanks :)

Anonymous said...

try{
var jqueryIsLoaded=jQuery;
jQueryIsLoaded=true;
}
catch(err){
var jQueryIsLoaded=false;
}

if(jQueryIsLoaded){
}
else{
}

I use this approach caue using an undefined variable jQuery in IE8 causes a crashing error

by carmichael84

Post a Comment