I'm currently reading Greg Franko's blog article on 'jQuery Best Practices'.
Among his early slides, he explains the typical/better/best ways of doing things.
Typical (link)
$("document").ready(function() {
console.log('hello world');
});
OR
$(function() {
console.log('hello world');
});
Better (link)
(function($, window, document) {
$(function() {
console.log('hello world');
});
}(window.jQuery, window, document));
Best (link)
(function(yourcode) {
yourcode(window.jQuery, window, document);
}(function($, window, document) {
$(function() {
console.log('hello world');
});
}));
So I guess my question is - what makes the third example better than the second example? Both are IIFE. The only difference I see is that #2 passes in the jQuery object (+ window + document) into the IIFE and runs the code then while #3 passes in the jQuery object (+ window + document) AND the JavaScript code into the IIFE. What is the benefit to that?
$
being used by other libraries as well, there are (rare) times when people try to use different versions ofjQuery
on same page. This was quite often in the early days of WordPress, when WP did not ship with jQuery and plugin/theme developers would ship their own version of it, obviously causing conflicts. That's the main reason why, by default, WP runs jQuery in.noConflict()
and requires a closure wrapper that passes it as reference. β Hite