Checking a jquery plugin exists before using it

Posted by davidejones

When creating a simple static website we all know there often isn’t the need to include all the javascript libraries you have on every page.

For example i often use fancybox for some nice popups of google maps etc so i will only need to include the fancybox jquery plugin on the contact us page and maybe a gallery page if i happen to use it there too. This works great but because i also keep my javascript which enables the plugins in a seperate file called common.js i run into a problem where i will get a few errors on the other pages saying it didn’t understand the property or function fancybox() because i didn’t include the library on those pages.

Sometimes this error can then prevent further javascript from executing and cause all kinds of problems you may be unaware of. A simple solution is to use a little check like this to make sure you have a plugin loaded or not.

if(jQuery().fancybox)
{
     // jquery fancybox is there now we can use it!
     $(".iframe").fancybox();
} else {
     // jquery fancybox hasn't been loaded
}

In this example i have just used fancybox but you should be able to use this in any other plugin such as the nivo slider etc.

This has become a common practice for me now just as i would use isset in php i now use this in javascript.

Trackback URL for this post: http://davidejones.com/blog/556-checking-jquery-plugin-exists/trackback/

Being Sociable...

  • If you like this article then please share it on your favourite social network and follow me on twitter for the latest updates

0 Responses to Checking a jquery plugin exists before using it

hups

hello how can i load all fancybox.js with mousscroll and easing.

sorry for bad english .

i will chek my website if fancybox already been loadet

for examble i have jquery load

var jQueryScriptOutputted = false;
function initJQuery() {

//if the jQuery object isn’t available
if (typeof(jQuery) == ‘undefined’) {

if (! jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;

//output the script (load it from google api)
document.write(“”);
}
setTimeout(“initJQuery()”, 50);
} else {

$(function() {
//do anything that needs to be done on document.ready
});
}

}

initJQuery();

an this for fancybox that was great.

can you help me ??

ok i have found it

if (typeof $.fancybox == ‘function’) {
//alert(‘fancybox has been already loaded so there is nothing left todo’);
}else {

//alert(‘I detected nada so I will load the fancybox js file ‘+pfad);
document.write(”);

document.write(”);

document.write(”);

document.write(”);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>