Ruud van Dijk Ruud van Dijk - 1 month ago 13
HTML Question

jQuery(...).plugin is not a function because js file is not loaded

I use a plugin (in this example it is selectric). I only load the plugin javascript file on product pages.

The code I use is:

jQuery('.myselectpicker').selectric({});
and is located in a custom javascript file witch is loaded on every page.

If I go to an other page then the product page, I get a
jQuery(...).selectric is not a function
error.

I understand why I get the error, because the plugin javascript file is not included in the head (only on product pages).

But is there something I can put around the
jQuery('.myselectpicker').selectric({});
code so it doesn't return an error on other pages than the product page?

I don't want to add the code to the plugin javscript file or in a seperate javascript file only loaded on the product page.

And for performance reasons I don't want to include all javascript files on every page type.

Answer

You can use jquery's isFunction function - https://api.jquery.com/jQuery.isFunction/

// Will trigger selectric() function only if it's lib included
if( $.isFunction( $.fn.selectric ) ){
    jQuery('.myselectpicker').selectric({});
} 
Comments