Reputation: 3470
I see many projects using
$(document).on('ready', function(e){
//jquery stuff
})
Instead of:
$( document ).ready(function( ) {
// Code using $ as usual goes here.
});
or
$(function() {
// Handler for .ready() called.
});
I read the complete api documentation but I don't see what is the case of use of the first example.
For me, the use of on
in the first example is useless.
What are the differences between the cases?
Upvotes: 12
Views: 21479
Reputation: 167172
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.
Upvotes: 21