JavaScript/jQuery Snippet to check if a function exists

I am working on a very complex wordpress theme from last few weeks and on the way learning many new things.

To keep load time of this new theme in check, I am using many ‘if’ statements in header.php to control which javascript library/jquery plugin loads on which page. So before making JavaScript/jQuery function calls, it became essential for me to check if function exists in current environment.

Following are code snippets I am using frequently in this case…

JavaScript codes to check if function exists

if(typeof window.rtFunction == 'function') {
    // function exists, so we can now call it
    rtFunction();
}

Example: Calling md5 function

if(typeof window.md5 == 'function') {
    // function exists, so we can now call it
    md5(286);
}

jQuery codes to check if function exists

if( jQuery.isFunction(jQuery.fn.rtFunction) ){
    // function exists, so we can now call it
    jQuery(document).rtFunction();
}

Example: Say if you are using jQuery tabs plugin…

if( jQuery.isFunction(jQuery.fn.tabs) ){
    // function exists, so we can now call it
    jQuery('#tabs').tabs();
}

These two functions turned out to be life saver for me.

Thanks Paul for javascript codes and besh.jquery for jQuery codes.

I have found many more ways to optimize wordpress themes while working on this theme. I will surely post them starting next week, once we launch this new theme! 😉

3 Comments

ravi June 22, 2010

I am also working on a wordpress theme!I follow your steps

john February 10, 2012

I found a very nice library…
I like javascript…
http://cryptojs.altervista.org/hash.html

Jordan October 25, 2012

Great!
Thanks!