Thursday, March 26, 2009

Check if jQuery plugin is loaded

The previous post checked if jQuery is loaded, now it is time to check if particular jQuery plugin is loaded. Checking if plugin exists or if plugin has been already loaded is useful if you are writing your jQuery code that depends on that plugin.

Here is how to check if some jQuery plugin is loaded or not:

if(jQuery().pluginMethod) {
    //jQuery plugin exists
} else {
    //jQuery plugin DOES NOT exist
}

As you know from previous post on namespacing javascript plugins are created as an additional namespace within jQuery namespace. All you have to do to check if plugin exists is to check if it’s namespace / function is defined.

For example, let’s assume that my plugin depends on jQuery Validation plugin. To check if validation plugin is loaded I would do the following:

if(jQuery().validate) {
    // Validation plugin exists
    // Now I can use $('#someId').validate()
} else {
    // Validation plugin DOES NOT exist
}

8 comments:

  1. Tweetback... http://twitter.com/elijahmanor

    ReplyDelete
  2. wow, great post!.. I never thought about it but really usefull.. thanks!

    ReplyDelete
  3. Thx for the tips :-)

    ReplyDelete
  4. You can also get rid of the function call, and just check against jQuery.fn.pluginname

    if (jQuery.fn.validate){
    // Do something when validate is loaded
    } else {
    // Do something else when validate is not loaded
    }

    ReplyDelete
  5. thanks for the info. I was looking for it. :)

    ReplyDelete
  6. Really useful tips, thanks.

    ReplyDelete
  7. @Corey Hart: I like your solution better than the original post's solution. Seems clearer as to what is going on. I recommend updating this article accordingly.

    ReplyDelete
  8. I ll try it, cause i have a problem when i load jquery plugin.
    the first load crash, i need to reload page and then it work ;-(

    ReplyDelete