简体   繁体   English

window.onload在iframe内调用了两次

[英]window.onload called twice inside an iframe

I'm testing events on an iframe and i came across something quite weird. 我在iframe上测试事件,我遇到了一些非常奇怪的事情。 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: 我有一个包含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: 和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上的onload事件运行两次,甚至更奇怪,看起来iframe本身被加载两次因为<h3>loaded</h3>元素控制台看起来像这样(变量我是两次'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. 要添加到怪异,如果我没有在父文件上附加onload事件,iframe的onload只能运行一次。

If you want to run it without interference just go to http://sureshots.andrepadez.com/iframetest/ 如果您想在不受干扰的情况下运行它,请访问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. 我需要知道我做错了什么,或者这是一个已知的问题,我该如何解决它。

When you modify the body.innerHTML property, it causes the entire body element to be reconsidered. 修改body.innerHTML属性时,会导致重新考虑整个body元素。 The iframe element is effectively removed from the DOM and is inserted again, causing it to load twice. iframe元素有效地从DOM中删除并再次插入,导致它加载两次。

The offending line: 违规行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM