For a while now, I’m been using jQuery to offer enhancements via JavaScript on my websites. However, I’m now beginning to ponder—from a performance point of view—what is the best way to organise my file of functions?
Up until now, I’ve done something similar to the following:
$(document).ready(function() {
foo();
bar();
});
function foo() {
// do something here
};
function bar() {
// do something else here, and so on...
};
However, I’ve since seen JavaScript file layouts like this:
$(document).ready(function() {
$(selector).foo();
$(selector).bar();
});
$.fn.foo = function() {
$(this).each(function() {
// do something here and return
});
};
$.fn.bar = function() {
$(this).each(function() {
// do something here and return
});
};
Is it better practice to extend jQuery and assign methods to a selector as in the second example? Or is it still OK to define individual functions as the first example?
It very much depends (the catch-all answer!). If a piece of functionality makes sense as a plugin i.e. can be reused in different ways on your site, then make it a plugin. Similarly, if a function is useful all over the place e.g. a date parsing function, make it a utility function.
There are a couple of points that I think are really worth bearing in mind – scope and pollution
scope
If a function needs to be in a scope that makes it accessible to functions in other scopes, then make it so. If it doesn’t, don’t. Which leads onto
pollution
try not to pollute the global namespace/object with numerous different functions. Organise your code into related functions by utilising object literals such that only one property is created on the global object that contains objects with properties containing related functions. For example,
In summary,