Immediately Invoked Function Expressions (IIFEs)
IIFEs are an ideal solution for locally scoping global variables/properties and protecting your JavaScript codebase from outside interference (e.g. third-party libraries). If you are writing jQuery code that will be run in many different environments (e.g. jQuery plugins), then it is important to use an IIFE to locally scope jQuery because you can’t assume everyone is using the $ to alias jQuery. Here is how you would do it:
// IIFE - Immediately Invoked Function Expression
(function($, window, document) {
// The $ is now locally scoped
// The rest of your code goes here!
}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
If you don’t like having to scroll to the bottom of your source file to see what global variables/properties you are passing to your IIFE, you can do this:
// IIFE - Immediately Invoked Function Expression
(function(yourcode) {
// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document);
}(function($, window, document) {
// The rest of your code goes here!
}
));
To read more about IIFEs, you can read my blog post titled, I Love My IIFE.
jQuery Ready Event
Many developers wrap all of their code inside of the jQuery ready event like this:
$("document").ready(function() {
// The DOM is ready!
// The rest of your code goes here!
});
Or a shorter version like this:
$(function() {
// The DOM is ready!
// The rest of your code goes here!
});
If you are doing either of the above patterns, then you should consider moving the pieces of your application (e.g. methods), that don’t depend on the DOM, outside of the ready event handler. Like this:
// IIFE - Immediately Invoked Function Expression
(function(yourcode) {
// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document);
}(function($, window, document) {
// The $ is now locally scoped
$(function() {
// The DOM is ready!
});
// The rest of your code goes here!
}
));
This pattern makes it easier to separate your logic (from a code design perspective) since not everything has to be wrapped inside of a single event handler callback function. It will also improve your application’s page load performance, since not everything needs to initialized right away. A great example of this is lazy binding DOM event handlers that do not need to be bound when the DOM is ready.
Adapted from my jQuery Best Practices blog post: http://gregfranko.com/blog/jquery-best-practices/