David David - 6 months ago 33
jQuery Question

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) {
RecursiveScriptLoader(0, scripts);

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

function QUnitStart() {
// I want to set document.ready = true right here!

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



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