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 inspect evt.target.src
in the event listener.
iframe.onload = function(evt) {
if (evt.target.src != '') {
// do stuff
}
}
(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 first onload
call, from my tests.
Study of iframe onload behavior in different situations
iframe.onload = function(evt){
console.log("frameOnload", ++i);
console.log("src = '" + evt.target.src + "'");
};
iframe onload behavior with regular URL
// Chrome: onload 1 src='', onload 2 src=requestedSrc
// IE11: onload 1 src=requestedSrc
// Firefox: onload 1 src=requestedSrc
document.body.appendChild(iframe);
iframe.src = "http://www.example.org/";
iframe onload behavior with 404 URL
// Chrome: onload 1 src='', onload 2 src=requestedSrc
// IE11: onload 1 src=requestedSrc
// Firefox: onload 1 src=requestedSrc
document.body.appendChild(iframe);
iframe.src = "http://www.example.org/404";
iframe onload behavior with non-resolvable (at DNS level) URL
// Chrome: onload 1 src='', onload 2 src=requestedSrc
// IE11: onload 1 src=requestedSrc
// Firefox: onload NEVER triggered!
document.body.appendChild(iframe);
iframe.src= 'http://aaaaaaaaaaaaaaaaaaaaaa.example/';
iframe onload behavior with iframe.src
explicitly set to about:blank
before appending to DOM
// Chrome: onload 1 src='about:blank', onload 2 src=requestedSrc
// IE11: onload 1 src=requestedSrc
// Firefox: onload 1 src=requestedSrc
iframe.src = "about:blank";
document.body.appendChild(iframe);
iframe.src = "http://www.example.org/";
iframe onload behavior with iframe.src
explicitly set to a javascript expression before appending to DOM
// Chrome: onload 1 src='javascript:void 0', onload 2 src=requestedSrc
// IE11: onload 1 src=requestedSrc
// Firefox: onload 1 src=requestedSrc
iframe.src = "javascript:void 0";
document.body.appendChild(iframe);
iframe.src = "http://www.example.org/";