Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready inside $(document).ready

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?

like image 479
David Groomes Avatar asked Mar 14 '14 20:03

David Groomes


People also ask

Can you put a function inside document ready?

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.

Can we have multiple document ready () function on the same page?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

What does $( document .ready function () do?

$( 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.

Should all jQuery be inside document ready?

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.


1 Answers

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:

  1. a
  2. c
  3. 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);
like image 91
zzzzBov Avatar answered Oct 15 '22 09:10

zzzzBov