动态创建的 iframe 触发两次 onload 事件 [英] dynamically created iframe triggers onload event twice

查看:45
本文介绍了动态创建的 iframe 触发两次 onload 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建了一个 iframe,发现这个 iframe 触发了两次 onload 事件.

I created an iframe dynamically and found that this iframe trigger onload event twice.

var i=0;
frameOnload=function(){
  console.log(i++);  
};

var ifr=document.createElement("iframe");  
ifr.src="javascript:(function(){document.open();document.write('test');document.close();})();";
ifr.onload=frameOnload;  
document.body.appendChild(ifr);

为什么我最终是 1?
如何防止 iframe 的 onload 两次而不是将 onload 函数指向自身内部的 null?

Why i finally is 1?
How to prevent iframe's onload twice instead of pointing onload function to null inside itself?

推荐答案

我也遇到了同样的问题,但是没有任何答案,所以我自己测试了.

I've also encountered the same problem, but get no answer anywhere, so I tested by myself.

如果在将 iframe 附加到正文之前附加 onload 事件,iframe onload 事件将在 webkit 浏览器 (safari/chrome) 中触发两次.

The iframe onload event will be triggered twice in webkit browsers ( safari/chrome ), if you attach the onload event BEFORE the iframe is appended to the body.

因此,您可以通过以下方式更改代码来防止 iframe 加载两次.

So you can prevent iframe onload twice by change your codes in the following way.

document.body.appendChild(ifr);
ifr.onload=frameOnload; // attach onload event after the iframe is added to the body

那么,你只会得到一个 onload 事件,也就是文档真正加载的事件.

Then, you will only get one onload event, which is the event the document really loaded.

这篇关于动态创建的 iframe 触发两次 onload 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆