I am reading this book "Secrets of the Javascript Ninja" where most of the code is demonstrated with the use of a custom assert. The code is as follows:
(function () {
var queue = [],
paused = false,
results;
this.test = function test(name, fn) {
queue.push(function () {
results = document.getElementById("results");
results = assert(true, name).appendChild(
document.createElement("ul"));
fn();
});
runTest();
};
this.pause = function () {
paused = true;
};
this.resume = function () {
paused = false;
setTimeout(runTest, 1);
};
function runTest() {
if (!paused && queue.length) {
queue.shift()();
if (!paused) {
resume();
}
}
}
this.assert = function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
if (results === undefined) results = document.getElementById("results");
results.appendChild(li);
if (!value) li.parentNode.parentNode.className = "fail";
return li;
};
})();
As you can see is a self invoking function.
I've been playing with it and something that I just cannot understand is why if, between the same tags, I do this:
<script type="text/javascript">
... previously shown code ...
window.onload = function(){
assert(true, "this works");
};
</script>
And then again if I just do the assert like this:
<script type="text/javascript">
... previously shown code ...
assert(true, "this does not work");
</script>
When I try to execute the assert without using the window.onload event I get the error "Uncaught TypeError: Cannot call method 'appendChild' to null" on the line "results.appendChild(li)" of the assert method.
Thank you so much for your help.
document.getElementByIdand tries to append to it - when the DOM is not already loaded this fails.