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?