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?
I've had this happen to asynchronously loaded stylesheets, like this one.
I find that the simplest solution is to have the event remove itself:
FWIW, while I was able to reproduce double
onload
in case whereiframe.src
isjavascript:
, I was not able to reproduce it with a normal HTTP URL (onload was happening once). However, when you change the order of calls so thatiframe.src
is set after appending to body, then the double-load happens (again, webkit only):When I assign
src
before appending, I get oneonload
call.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 codes in the following way.
Then, you will only get one onload event, which is the event the document really loaded.
To expand on the top-voted answer: if you can not control when and how things are attached to the DOM -- for instance, when using a framework (we've had this happening in our Angular app) -- you might want to try the solution below.
I did heavy cross-browser testing and I found the following workaround: check the parameter passed to
onload
callback and inspectevt.target.src
in the event listener.(if you call global method from HTML, remember to pass
event
in your HTML markup:<iframe onload="window.globalOnLoad(event)">
)evt.target.src
can be be''
(empty string) only in webkit in the firstonload
call, from my tests.Study of iframe onload behavior in different situations
iframe onload behavior with regular URL
iframe onload behavior with 404 URL
iframe onload behavior with non-resolvable (at DNS level) URL
iframe onload behavior with
iframe.src
explicitly set toabout:blank
before appending to DOMiframe onload behavior with
iframe.src
explicitly set to a javascript expression before appending to DOM