$(document).ready(function() VS $(function(){ [duplicate]

Possible Duplicate:
what is difference of $(function(){ }); and $(document).ready(function() { }) ;?

What are the differences between $(document).ready(function(){}) vs $(function(){}) and should I write it in the $ form or the new jQuery(document).ready(function(){ }) way?

If I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?

I've also seen people use $(function($){})

Can somebody help me, I'm lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?


Solution 1:

The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.

About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.

The argument that the ready handler function receives, is the jQuery object itself.

That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:

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

The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.

Solution 2:

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

The two statements are actually the exact same. So the second call is just a shortcut for the first.

The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned

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

call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.

Solution 3:

I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.

http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner