Have you ever been in a position where you only want to load JavaScript files on pages where they are being used but are calling a jQuery function that throws an error on the page and no other jQuery is loaded as result?
I was in this position recently and found a simple way to check whether a jQuery function exists!
Basically I had a form that was being used site-wide but the client wanted me to dequeue these scripts on a few landing pages that weren’t using the form.
I was using an if/else structure to determine which JavaScript files were loaded based on the page slug. The problem was that if I didn’t load the JavaScript file with a specific function then an error was created that killed all JavaScript on the page.
I searched and finally found a solution that worked.
if ($.fn.spinner) {
// there is some jquery plugin named 'spinner' on your page
$( "#input_92_31" ).spinner({
min: 0,
max: 100000,
step: 5000,
start: 20000,
numberFormat: "C",
culture: "en"
});
}
This will check to see if the jquery plugin is being loaded first then will load the custom jquery code only if the plugin itself is loaded.
You will need to replace .spinner with the name of plugin you wish to check for.
This provided a simple solution to my problem. Let me know if you found this helpful or if you need some help finding a solution to your development problem. Thanks!
Leave a Reply