1

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.

Community
  • 1
  • 1
P Jones
  • 1,077
  • 1
  • 9
  • 14
  • You should be assigning `makeDocument` to `window.onload`, not invoking it. Drop the `()`. –  Jan 17 '15 at 18:00
  • The reason the ` –  Jan 17 '15 at 18:02
  • That was it! Simple as that. All that time to write this up and all I had to do was hit backspace twice. – P Jones Jan 17 '15 at 18:07
  • One more question: so what was happening was that when I was trying to assign the function to `window.onload`, I was actually invoking the function? – P Jones Jan 17 '15 at 18:09
  • Yes, it was being invoked, and its return value was being assigned to `window.onload`. In the case of that function, the return value was `undefined`. –  Jan 17 '15 at 18:10

0 Answers0