I'm trying to detect when an iframe and its content have loaded but not having much luck. My application takes some input in text fields in the parent window and updates the iframe to provide a 'live preview'
I started with the following code (YUI) to detect when the iframe load event occurs.
$E.on('preview-pane', 'load', function(){
previewBody = $('preview-pane').contentWindow.document.getElementsByTagName('body')[0];
}
'preview-pane' is the ID of my iframe and I'm using YUI to attach the event handler. However, trying to access the body in my callback (upon iframe load) fails, I think because the iframe loads before the event handler is ready. This code works if I delay the iframe loading by making the php script that generates it sleep.
Basically, I'm asking what is the correct approach across browsers to detect when the iframe has loaded and its document is ready?
This question is related to
javascript
events
cross-browser
For those using React, detecting a same-origin iframe load event is as simple as setting onLoad
event listener on iframe element.
<iframe src={'path-to-iframe-source'} onLoad={this.loadListener} frameBorder={0} />
For anyone using Ember, this should work as expected:
<iframe onLoad={{action 'actionName'}} frameborder='0' src={{iframeSrc}} />
See this blog post. It uses jQuery, but it should help you even if you are not using it.
Basically you add this to your document.ready()
$('iframe').load(function() {
RunAfterIFrameLoaded();
});
Source: Stackoverflow.com