Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is difference between $( document .ready function (){ vs $( function (){?

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).

What does $( document .ready function () mean?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

What is replacement of $( document .ready function?

load(function(){ // ...}) @undefined, this is almost the same as $(document). ready(function(){ ... }) . load() will wait until the graphics are also loaded.

Can you have multiple $( document .ready function ()?

ready' function in a page? Can we add more than one 'document. ready' function in a page? Yes we can do it as like I did in below example both the $(document).


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.


  • $(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.


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