This is a corollary to my last question, and possibly an extension of this one. I was playing with createHTMLDocument()
, trying to set an onload
event to trigger it. The following code (based on code found here) uses an inline onload
and works just dandy:
<div>
<iframe id="frame" src="about:blank"> </iframe>
</div>
<script>
function makeDocument() {
var frame = document.getElementById("frame");
var doc = document.implementation.createHTMLDocument("New Document");
var p = doc.createElement("p");
p.innerHTML = "This is a new paragraph.";
doc.body.appendChild(p);
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
console.log(destDocument.readyState);
}
</script>
<body onload="makeDocument()"></body>
However, if I try to load makeDocument()
with window.onload
the function fires too early, before something (not sure what) that is required by createHTMLDocument()
is loaded. Here's the code (with some redundancies removed):
<div>
<iframe id="frame" src="about:blank"> </iframe>
</div>
<script>
function makeDocument() {
// same as previous
}
window.onload = makeDocument();
</script>
If you run this you'll notice that not only is the text not added to the frame, but that, as the console output indicates, the inner document cannot be initialized at the time window.onload
is fired. Why not?
I have read in various places that window.onload
and inline onload
are essentially the same thing. But then maybe not really. If anyone could explain this to me you'd make me a very happy person indeed.