beeker beeker - 5 months ago 36
Javascript Question

window.onload not Firing in Embedded html Document

I'm trying to embedd two html documents in another using javascript. The problem I am having is that the onload event does not fire on the embedded document.

paper.htm has several div tags and should contain curve.htm but in curve.htm the onload event is not firing

paper.htm

<html>
<head>
<title>Curve</title>
<script>
(function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'curve.htm', true);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById('chartBlock').innerHTML = this.responseText;
}
xhr.send();
})();
</script>
</head>
<body>
<div id="paper">
<div id="border">
<div id="chartBlock"></div>
<div id="titleBlock"></div>
</div>
</div>
</body>
</html>


curve.htm (partial)


<html>
<head>
<script src="File:///Temp/curveData.js" type="text/javascript"></script>
<script>
window.onload = init; //this never fires!
function init() { //... }
</script>
<body>
<canvas id="chartCanvas" width="954" height="625"></canvas>
</body>
</html>


I have tried:


  1. Using jquery to load the html document (many examples here on SO).

  2. Putting onload in the body tag of the html document (curve.htm)



tried with jquery:

<script>
$(function () {
$("#chartBlock").load("curve.htm");
$("#titleBlock").load("titleblock.htm");
});
</script>


tried with html:

<body onload="init()">


Any other ideas to look into would be very much appreciated. Thanks

Answer

Because the document will not be loaded...

What you are doing could be achieved with iframes. With an iframe, you are loading a full html document, which will be parsed as such. With the $.load function, you will just bluntly insert html, which will be parsed as <body>'s children. Meaning; the <head>, <meta> tags etc. will be ignored by all/proper browsers, because they should only occur inside the head of a document. Simplified, your output would be:

<html>
    <head>
        <!-- whatever -->
    </head>
    <body>

        <div id="chartBlock">
            <html>
                <!-- What?! Another html tag?! -->
            </html>
        </div>
        <div id="titleBlock">
            <html>
                <!-- And another one... -->
            </html>
        </div>

    </body>
</html>

So, what you want to do, is loading only the contents, what would be inside the <body> tag, and use the success callback of the $.load function to do whatever you want to do if the contents are inserted in your document.

Comments