I have site which is using a few JavaScript/jQuery plugins, I then have a default.js file which uses the plugin functionality for each of the different pages.
E.g. some plugins I have include:
- a custom scrollbar plugin
- a slideshow plugin
- a cookie plugin
- etc.
Then in the default.js file, I’ll do something as follows (pseudocode):
var scrolling = findScrollbarDiv;
scrolling.ScrollFunction({ options });
(and then the same for the slideshow + other plugins I have)
However, if there is a plage where findScrollbarDiv returns null, I get an error something like the following:
ScrollFunction is not a function
This is not because the elements are returning null, but because I haven’t included the plugin file for this page. My reasoning behind this is that I don’t want to include every file on every page (even if it’s not needed) as this could cause unnecessary HTTP requests (especially on the homepage, which only needs one plugin)
This error in turn messes up the rest of the JavaScript.
What is the best way to overcome this? Should I just include every plugin file on every page regardless of whether it is needed or not? Or is there some JavaScript like the following that I can use:
var scrolling = findScrollbarDiv;
if(scrolling != null) {
scrolling.ScrollFunction({ options });
}
(this feels a bit clunky to me, but if this is the best solution let me know)
Or is using one default js file to launch all plugins a bad idea?
If you’re using the same header file and you don’t mind having the file included, you can always check if the element exists before attaching an event to it.
Heres an example:
Either that, or have a JavaScript file for each function.
So you’d have one for the gallery and one for the cookies etc.. And include only the ones necessary for each page.