$(Document).Ready(Function() VS $(Function(){

$(document).ready(function() VS $(function(){

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.

What's the difference between $(document).ready(…) and $(function() {}) in jQuery?

$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)

are equivalent.

Actually, you can call .ready(handler) on any jQuery object, no matter what it contains, and it will do the same thing:

ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();

// Add the callback
readyList.add( fn );

return this;
},

What's the difference between $(document).ready() and just omit it?

<script> tags in your HTML that do not have the defer or async attributes will execute in the order the HTML document is parsed from top down. That means that a script near the top of the document will execute before the rest of the document has been parsed and thus before it is available. This makes the placement of a script or the execution timing of a script relevant in many cases.

In controlling this execution timing, you have at least five choices for executing startup scripts:

  1. You can put the script in the <head> section or the top of the <body> section and execute it as it loads. This has the disadvantage that the DOM is not yet loaded so you can't operate on elements within the page.

  2. You can insert the script right before the </body> tag and all of the DOM will be loaded and your script will be able to access everything.

  3. You can insert your script anywhere you want (including in the <head> tag) and use $(document).ready(fn) to not execute the fn until the DOM is ready. Internally, jQuery listens for the DOMContentLoaded event and when it fires, it executes any .ready() handlers.

  4. You can insert your script anywhere you want (including in the <head> tag) and use window.onload(fn) to not execute the fn until the DOM is ready and all external resources such as images have loaded. Note, you can also use the jQuery version $(window).load(fn).

  5. You can use the async or defer attributes on the script tag to force it to load asynchronously and somewhat later. This will create an indeterminate time of script execution (though always later than if it was just inline) so you will likely need some specific control like $(document).ready() to know that the DOM is safe before your script executes. You can see these other questions/answers Script Tag - async & defer and Load and Execute order of scripts for a lot more details on the operation of the async and defer attributes.

So, if you carefully place your script tag in the right place or your startup script does not try to access DOM elements, you don't need to use either $(document).ready(fn) or window.onload(fn).

But, if you don't entirely control where the script is placed and you need to access DOM elements or you want your script to be able to be placed anywhere and still have it do the right thing or if you just want all your scripts in the <head> tag, then you will need to delay the execution of your script until the DOM is ready and either $(document).ready(fn) or window.onload(fn) will make it easy to do so.

What is the difference between these jQuery ready functions?

Nothing whatsoever.

This function behaves just like
$(document).ready(), in that it should
be used to wrap other $()

You can see this in the source code:

rootjQuery = jQuery(document);

...

} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}

jQuery $( function() {} ) and $(document).ready the same?

See the extract below from http://api.jquery.com/ready/

All three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)

$(document).ready(function(){}); vs script at the bottom of page

Very little in and of itself, either way the DOM will be ready for you to operate on (I was nervous about that until I read this from Google). If you use the end of page trick, your code may get called the slightest, slightest bit sooner, but nothing that will matter. But more importantly, this choice relates to where you link your JavaScript into the page.

If you include your script tag in the head and rely on ready, the browser encounters your script tag before it displays anything to the user. In the normal course of events, the browser comes to a screeching halt and goes and downloads your script, fires up the JavaScript interpreter, and hands the script to it, then waits while the interpreter processes the script (and then jQuery watches in various ways for the DOM to be ready). (I say "in the normal course of things" because some browsers support the async or defer attributes on script tags.)

If you include your script tag at the end of the body element, the browser doesn't do all of that until your page is largely already displayed to the user. This improves perceived load time for your page.

So to get the best perceived load time, put your script at the bottom of the page. (This is also the guideline from the Yahoo folks.) And if you're going to do that, then there's no need to use ready, though of course you could if you liked.

There's a price for that, though: You need to be sure that the things the user can see are ready to be interacted with. By moving the download time to after the page is largely displayed, you increase the possibility of the user starting to interact with the page before your script is loaded. That's one of the counter-arguments to putting the script tag at the end. Frequently it's not an issue, but you have to look at your page to see whether it is and, if so, how you want to deal with it. (You can put a small inline script element in the head that sets up a document-wide event handler to cope with this. That way, you get the improved load time but if they try to do something too early, you can either tell them that or, better, queue the thing they wanted to do and do it when your full script is ready.)

$(document).ready() or $(function()) -- Which to use?

I use $(document).ready(function(){}); despite the additional typing. I just prefer having that in my code to remind me exactly when the code is going to run, and for the ability to search for 'ready' to find those sections. It's the same functionality, and I normally take shortcuts, but in this case I don't.

Differences between $(document).ready(function(){}) and $(document).on('ready', function(e)

The function:

$( document ).ready(function ( ) {
// Code using $ as usual goes here.
});

Translates to:

$( document ).on( 'ready', function (e) {
//jquery stuff
})

This is the same with these shorthand functions:

$( element ).click( function ( ) { } );
$( element ).hover( function ( ) { } );
$( element ).load( function ( ) { } );
$( element ).scroll( function ( ) { } );

From the documentation of .click( handler(eventObject) ):

This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third.


Updated Answer - The difference!

There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8
. This behaves similarly to the ready method but if the
ready event has already fired and you try to .on( "ready" ) the bound
handler will not be executed. Ready handlers bound this way are
executed after any bound by the other three methods above.

-- Source

Update #2

jQuery(function(){});

should also be considered as a shorter alternative to

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

It is genuinely prefered since it does not reduce readability and removes a few bytes of character.

$(document).ready(function() vs .click(function()

The ready event is fired when your dom page is loaded.

Your getJSON() function is triggered after the dom is loaded !

Add a promise to your getJSON code to change it.

.getJSON().then(function() {
$("#one").toggle(data.indexOf("one") !== -1);
$("#two").toggle(data.indexOf("two") !== -1);
$("#three").toggle(data.indexOf("three") !== -1);
$("#four").toggle(data.indexOf("four") !== -1);
});


Related Topics



Leave a reply



Submit