Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 330
Sergio Avatar asked Aug 06 '11 22:08

Sergio


People also ask

What is document ready in jQuery?

jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.

What is JavaScript equivalent of document ready?

jQuery $(document). ready() Equivalent in JavaScript This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

How do you call a document ready function?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).

What is difference between $( function () and document Ready?

There is no difference in functionality between your examples - they both bind to DOM ready. For reference, there are two points at which you can bind your jQuery code. The first will execute when the DOM is ready (both are equivalent): // full example $(document).


1 Answers

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

});
like image 171
user113716 Avatar answered Oct 22 '22 14:10

user113716