I found code in my codebase that has $(document).ready(function() {...}
inside of another $(document).ready(function() {...}
e.g.
$(document).ready(function() {
// 20 lines...
$(document).ready(function() {
foo()
}
// 200 lines...
}
function foo() {...}
I want to understand the order of execution so I can safely refactor out this nested callback. The outer callback seems to continue executing before the inner callback executes. Is the outer callback guaranteed to finish before the inner callback gets called?
Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.
Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.
$( 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.
Answer. No, they don't. When using jQuery we can define the functions we want to use after our document is loaded, inside of jQuery's . ready() method.
Is the outer callback guaranteed to finish before the inner callback gets called?
Yes.
The way document.ready
works is that it will wait for the readystatechange event to fire as being ready before the callback gets called, however it also runs setTimeout
if the readystatechange event has already fired.
This means that code such as:
$(function () {
a();
$(b);
c();
});
Where a
, b
, and c
are all functions will execute in the order of:
a
c
b
On a related note, people will question why you would want to run a document.ready
call inside another document.ready
call, and the short answer is that you wouldn't.
The only gain is that $(callback)
is a bit more convenient to write than:
setTimeout(callback, 0);
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