Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 927
David Avatar asked May 16 '11 20:05

David


People also ask

How do I delay the document ready event?

Approach 1: Using the holdReady() method in the jQuery library and the setTimeout() method. First we set the parameter in the holdReady() method to true to hold the execution of the document. ready() method. Then, a timeout function with an appropriate delay time can be added using the setTimeout() method.

Is it possible to hold or delay document ready execution for some time?

Yes, with jQuery.

Does document ready only run once?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Which jQuery method helps the caller to delay jQuery's Ready event?

holdReady() method allows the caller to delay jQuery's ready event. This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready.


1 Answers

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).

like image 200
mVChr Avatar answered Oct 05 '22 15:10

mVChr