Sergio
Sergio

Reputation: 1077

Different ways of saying document ready in jQuery?

Are these both the same thing, i.e. ways of saying document ready:

$(function() {
  //
});

and

$(function($) {
   //
})(jQuery);

or is there a difference between the two, if so then when should I use which?

Upvotes: 8

Views: 3927

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69905

They both are not same.

First code block is used to execute the function on document ready where as second code block is used when we want to execute the code block immediately without waiting for rest of the code to be loaded. But there is some error in your second part of the code. It should be as below.

(function($) {
   //
})(jQuery);

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

This one is incorrect:

$(function($) {
   //
})(jQuery);

You're passing a function to $(...), then calling the result. However, the result of $(...) is a jQuery object, which is not a function. You might see it better this way:

$(

    function($) {
        //
    }

)

(jQuery);

Generally, there are three versions of document.ready, which are all equal to each other:

$(function() {...});

$(document).ready(function() {...});

$().ready(function() {...});

Upvotes: 0

user113716
user113716

Reputation: 322472

The first one is a shortcut for .ready().

The second one is simply invalid as you're trying to call a non-callable object.

You probably meant this:

// v--------no $ at the beginning
    (function( $ ) {

       // simply a new lexical environment with a 
       //        local $ parameter pointing to jQuery

    })(jQuery);

...though it has nothing to do with DOM ready.

There is a variation on your first example that combines the two:

jQuery(function( $ ) {

  // DOM ready, and creates a local $ parameter pointing to jQuery

});

Upvotes: 9

Related Questions