window.onload called twice inside an iframe

I'm testing events on an iframe and i came across something quite weird. I have looked around for other people with the same problem but found none exactly with these characteristics.

I have a page that contains an iframe:

<!-- index.html -->
<body>
    <h1>Parent</h1>
    <h4><a href="index2.html">...go to the 2nd page...</a></h4>
    <iframe src="iframe.html"></iframe> 

    <script type="text/javascript">
        window.addEventListener('load', function(){
            console.log('parent loaded');
        });
    </script>

</body>

and the iframe:

<body>
    <h1>Iframe</h1>
    <script type="text/javascript">
        var i = 0;
        window.addEventListener('load', function(){
            window.top.console.log('iframe loaded', i++);
            document.body.innerHTML += '<h3>loaded</h3>';
        });
    </script>
</body>

When i load the page, the onload event on the iframe is run twice and, more weird even, it looks like the iframe itself is being loaded twice because the <h3>loaded</h3> element the console looks like this (the variable i is twice '0'):

iframe loaded 0     iframe.html:11
parent loaded       (index):13
iframe loaded 0     iframe.html:11

To add to the weirdness, if i don't attach the onload event on the parent file, the iframe's onload runs correctly, only once.

If you want to run it without interference just go to http://sureshots.andrepadez.com/iframetest/

I need to know if i'm doing something wrong or if this is a known issue and how can i fix it.

Upvotes: 1

Views: 5429

Answers (1)

John Sterling
John Sterling

Reputation: 1111

When you modify the body.innerHTML property, it causes the entire body element to be reconsidered. The iframe element is effectively removed from the DOM and is inserted again, causing it to load twice.

The offending line:

document.body.innerHTML += '<h3>loaded</h3>';

Upvotes: 8

Related Questions