Home >Web Front-end >JS Tutorial >Solution to the bug where iframe's onload is executed twice in Chrome/Opera_javascript skills

Solution to the bug where iframe's onload is executed twice in Chrome/Opera_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 18:09:051500browse
Copy code The code is as follows:





iframe's onload is executed twice in Chrome/Opera

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


The solution is very simple, just change the order of the code: create an iframe, add it to the body, and finally add the load event. Will behave the same across all browsers.
Copy code The code is as follows:

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

In addition, I tested it with Safari 5. There is no alert, it keeps loading, and it can last for more than 30s. Would you like to give it a try?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn