Reputation: 6499
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:
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?
Upvotes: 0
Views: 161
Reputation: 1608
You can just do it as a conditional statement and avoid the clunky if:
scrolling && scrolling.ScrollFunction({ options });
This works great for any method you want to call and want to check if the parent object exists before you do. You can go further (if you need to) and check if the method itself exists before execution:
scrolling && scrolling.ScrollFunction && scrolling.ScrollFunction({ options });
if scrolling is a collection, just check it's length (if length == 0 the statement will fail):
scrolling.length && scrolling.ScrollFunction({ options });
Upvotes: 1
Reputation: 3082
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:
if(jQuery('#someElement').length > 0){
jQuery('#someElement').ScrollFunction({ options });
}
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.
Upvotes: 1