How can I delay document.ready until a variable is set?

David picture David · May 16, 2011 · Viewed 11.9k times · Source

I am doing QUnit testing in an IFRAME and have a recursive JavaScript function that loads all of the scripts from the parent page into the IFRAME before starting QUnit. This works great. My problem is that some of our scripts use document.ready to make stuff start.

Something such as:

$(document).ready(function () {
    // blah
});

to do do their work. I'd prefer to not change production code just to account for tests and I don't want these production scripts to think the IFRAME document is "ready" until every scripts is loaded.

How I can delay "document.ready" itself?

Here is my pseudocode to give you an example to work from:

scripts[0] = "/foo/bar.js";
scripts[1] = "/blah/blah.js";

function RecursiveScriptStart(){
    // I want to set document.ready = false right here!
    if(scripts.length == 0) {
        QUnitStart();
        return;
    }
    RecursiveScriptLoader(0, scripts);
}

function RecursiveScriptLoader(currentScriptID, scripts) {
    $.getScript(scripts[currentScriptID], function () {
        if (currentScriptID == (scripts.length - 1)) {
            QUnitStart();
        }
        else {
            RecursiveScriptLoader(currentScriptID + 1, scripts);
        }
    });
}


function QUnitStart() {
        // I want to set document.ready = true right here!
        QUnit.stop();
        QUnit.start();
}

The actual code is similar, but involves a jquery selector populating the array "scripts[]" with JavaScript tag "src" properties.

Thanks!

Answer

mVChr picture mVChr · May 16, 2011

If you're using jQuery 1.6+ then you can use holdReady. Just set $.holdReady(true) at the top of your script and then in the beginning of QUnitStart set $.holdReady(false).