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?
The $(document). ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded.
$( document ). ready() A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
The main differences between the two are: Body. Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document. ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With