Gabriel Hansen
Gabriel Hansen

Reputation: 45

Best way to invoke an anonymous function and jQuery(document).ready()?

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

Answers (2)

user3274473
user3274473

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

Felix Kling
Felix Kling

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

Related Questions