iframe的onload在Chrome/Opera中执行两次Bug

创建iframe对象,添加load事件, 再将iframe添加到body中。Chrome/Opera中会造成load事件的handler执行两次。

<!DOCTYPE HTML>
<html> 
<head> 
	<meta charset="utf-8"> 
	<title>iframe的onload在Chrome/Opera中执行两次</title>
</head> 
<body>
	<script>
		var ifr = document.createElement('iframe');
		ifr.onload = function(){alert(1);};
		document.body.insertBefore(ifr,document.body.childNodes[0]);
		ifr.src = 'http://www.baidu.com';
	</script>
</body>
</html>

解决方法很简单,改下代码顺序即可:创建iframe, 添加到body中,最后添加load事件。所有浏览器下将表现一致。

var ifr = document.createElement('iframe');		
document.body.insertBefore(ifr,document.body.childNodes[0]);		
ifr.src = 'http://www.baidu.com';
ifr.onload = function(){alert(1);};

此外用Safari5测试,没有alert,一直在载入中,能持续30s以上。大家试试看呢?

posted on 2011-03-16 11:04  snandy  阅读(4138)  评论(2编辑  收藏  举报