I was researching on jQuery best practices and found this article by Greg Franko
Normally, I do:
$("document").ready(function() {
// The DOM is ready!
// The rest of the code goes here
});
But the article recommends to use:
// IIFE - Immediately Invoked Function Expression
(function($, window, document) {
// The $ is now locally scoped
// Listen for the jQuery ready event on the document
$(function() {
// The DOM is ready!
});
// The rest of the code goes here!
}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
I can see the comments there, but I couldn't figure out what it exactly saying.
So, which is the better approach and why?
I know that both methods will work, but how does the second one become the better?
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:
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:
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:
Or a shorter version like this:
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:
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/