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!
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.
Yes, with jQuery.
$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With