I've been playing around with adding hidden iframe elements to a page, and I want to manipulate the DOM of the these once loaded. I've noticed that I can't start manipulating the DOM immediately after adding the iframe to a page since it hasn't loaded yet. This can't be done with the DOMContentLoaded
event since that fires against the document which doesn't exist in the iframe until it is added to the page, so we have to use the load
event.
Here is some test code:
var iframe = document.createElement('iframe');
iframe.onload = function() { console.log('loaded!'); };
document.getElementsByTagName('body')[0].appendChild(iframe);
This works as expected, however when I change it to addEventListener
it doesn't even get added to the DOM:
var iframe = document.createElement('iframe');
iframe.addEventListener('load', function() { console.log('loaded!'); });
document.getElementsByTagName('body')[0].appendChild(iframe);
I haven't tested attachEvent
in IE.
Anyone shed any light on this?
addEventListener()
function needs 3 arguments! Take a look at https://developer.mozilla.org/en/DOM/element.addEventListenerThe 3rd argument is marked as optional, but then they write:
I'm not sure when and where it is required, but my tests on FF4 threw an exception when calling the
addEventListener
with 2 arguments:By the way, your code works well in Chrome [the string
loaded!
is logged in console].Like FF, IE9 needs the 3rd argument in the standards mode (with
<!DOCTYPE html>
). IE9 is the first IE that supports W3C's event model. So in the earlier versions we need to tryattachEvent
. I don't have earlier IEs, but it worked in IE7/8 Standards Mode and even in Quirks Mode in IE9. Here is the code I used: