Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  76] [ 7]  / answers: 1 / hits: 35005  / 12 Years ago, mon, may 28, 2012, 12:00:00

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);


Why i finally is 1?

How to prevent iframe's onload twice instead of pointing onload function to null inside itself?


More From » iframe

 Answers
49

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


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.


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


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

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


[#85313] Friday, May 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;