1

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.

0

2 Answers 2

1

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({});
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx that was exactly what I was looking for. Didn't know about the isFunction function.
0

An alternative to check if selectric is loaded is to check if any elements on your page need it, ie:

if (jQuery('.myselectpicker').length > 0)
    jQuery('.myselectpicker').selectric({});

this will then give an error - so could be combined with isFunction (see other answer, no need to repeat here) - but, will let you know which pages need the plugin but are missing it, rather than just missing functionality without warning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.