Topic on Talk:Learning JavaScript

jQuery document ready shortcut confusion

5
Krinkle (talkcontribs)

Since I ended up repeating this all over the place I might as well put it here for easy reference.

The following is an example that I would describe as an Immediately-Invoked Function Expression (IIFE) that has a local $ variable as argument, and called with the global jQuery-object as first argument. Inside of that was a jQuery ready event binder to the document:

( function ( $ ) {

	$( document ).ready( function () {
		/* code here */
 	} );

}( jQuery ) );

The reason we use this is because we want to locally alias jQuery to $. If all your code needs to be within the document ready bound function, you can use the ready-call to alias your variable, no need for an extra function:

jQuery( document ).ready( function ( $ ) {
	/* code here */
} );

If you're unfamiliar with this function you may think there's something missing here. There is "( $ )" but there is no "( jQuery );", right ? Well, here's where the difference between a locally called function and a remote callback comes in. The function passed to jQuery(document).ready is not called by you, instead it is called by jQuery's internals, at the time the document is ready. It is called like this: callbackFunction( jQuery );.

Afterall, $(document).ready isn't used like $(document).ready( fn )( jQuery ); either, that would be invalid.

So that leaves one thing, what is the following ?

jQuery( function ( $ ) {
	/* code here */
} );

Before we answer that, let's make clear what the jQuery root function (or rather, jQuery.fn.init) is. It is a shortcut to following three things:

In code snippet I use the latter (document.ready binder). This shortcut also has a slight advantage of using a cached version of jQuery(document) so there's no new jQuery object constructed for it.

This post was hidden by He7d3r (history)
This post was hidden by He7d3r (history)
This post was hidden by He7d3r (history)
Neelasdfsd (talkcontribs)

history for my side

Reply to "jQuery document ready shortcut confusion"