Reputation: 45
Is this redundant?
jQuery(document).ready(function($} {
//stuff
}(jQuery));
This is ugly and overly verbose:
(function($) { $(document).ready(function() {
//stuff
})})(jQuery);
What I need:
Just about the entire script runs after the dom is ready. Nesting .ready() in an anonymous function on different lines isn't ideal, because almost the whole file would end up being double tabbed.
What's the best way?
Upvotes: 0
Views: 73
Reputation:
regarding this:
(function($) { $(document).ready(function() {
//stuff
})})(jQuery);
this is basically wrapping the jQuery's
version of document-ready
function:
$(document).ready(function() {
//stuff
});
in an IIFE
:
(function($) {
// on-ready-function
}(jQuery));
which might be useful if you need to additionally encapsulate variables, etc.
But I usually do this:
$(function() {
//stuff
});
and have not had any problems with this (in my 10 years career).
One thing to note is to always put scripts at the end of the body.
Upvotes: 2
Reputation: 816334
jQuery already passes a reference to itself to the ready callback, so just do
jQuery(document).ready(function ($) {
//stuff
});
// or shorter
jQuery(function ($) {
//stuff
});
Btw, this
jQuery(document).ready(function ($) {
//stuff
}(jQuery));
would even be wrong. It calls the anonymous function immediately, with jQuery
as argument and then passes the return value to jQuery(document).ready()
.
Upvotes: 2