Search code examples
javascriptjqueryjquery-callbackasynccallback

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


Solution

  • 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);