Suppose, I have a js file which looks like this:
$(document).ready(function() { // first task} ); $(document).ready(function() { // second task } ); $(document).ready(function() { // third task } );
Upon loading the file the tasks get executed in order. I am not able to understand why ? I'm guessing that the callback methods are fired when an "on ready" event occurs. How is the execution order being retained ? Are the consecutive call backs being queued up in some place ?
Note: I know that this is a very naive way of coding. I have written the snippet only to get my point across and do not write such code in my projects.
jQuery ready() MethodThe ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.
The jQuery document ready function executes when the DOM (Document Object Model) is completely loaded in the browser. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery. The Javascript/jQuery code inside the $(document).
So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.
Your handlers are being pushed into an array (readyList
) for executing in order later, when the document
is ready.
They're queued like this:
readyList.push( fn );
And executed when ready like this:
var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); }
If the document is already ready, then they'll execute immediately, which is still in order.
The functions which you specify are in order added to a list. When the DOM is ready, jQuery iterates through that list and invokes the functions in that order.
Your list becomes something like..
handlers = [ function(){ alert('first') }, function() { alert('second')} ];
Then a loop iterates through...
for ( var i = 0, l = handlers.length; i<l; ++i ) { handlers.apply( document, arguments ) }
And the functions are called in the context of the document.
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