I was researching on jQuery best practices and found this article by Greg Franko
Normally, I do:
$(\"document\").ready(function() {
// The DOM i
The only difference between your code and the "suggested" approach is compatibility and possibly better compression. There are no speed differences.
Passing window.jQuery
as the first argument to your IIFE (immediately-invoked function expression) and naming it $
within the IIFE will just allow you to use jQuery without interfering with other libraries that assign themselves to the global $
. If you don't use any other libraries that assign themselves to the global $
, the first argument to your IIFE isn't going to serve any purpose.
Passing window
and document
to your IIFE will allow JS minifiers to transform your code into something like this (without the whitespace), which gives you slightly better compression:
(function(a, b, c) {
a(c).ready(function() {
// ...
});
})(window.jQuery, window, document);
Unless you use window
and document
extensively, I would just do:
;(function($) {
$(function() {
...
});
})(jQuery);
You can use document ready event using jquery, event occure when document is fully loaded.
$(function () {
setTimeout(function () {
// your code
}, 0);
})
If you use $ as an alias for jQuery then
$(document).ready(function(){})
is same as
(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));
As pointed out in an earlier answer, the second method insulates you from using $ alias freely for jQuery as it passes the jQuery object to the Immediately invoked function expression, which basically keeps the variables and code within it private, and does not pollute the global namespace.
In short, if you resort to the first method and use other libraries using $, you will end with conflict.