jQuery iframe load() event? jQuery iframe load() event? ajax ajax

jQuery iframe load() event?


use iframe onload event

$('#theiframe').on("load", function() {    alert(1);});


If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.

In the main document:

function iframeLoaded() {    alert("Iframe loaded!");}

In the iframe document:

window.onload = function() {    parent.iframeLoaded();}


Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:

In the iframe:

<script>    $(function() {        var w = window;        if (w.frameElement != null                && w.frameElement.nodeName === "IFRAME"                && w.parent.jQuery) {            w.parent.jQuery(w.parent.document).trigger('iframeready');        }    });</script>

In the containing page:

<script>    function myHandler() {        alert('iframe (almost) loaded');    }    $(document).on('iframeready', myHandler);</script>

The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.

This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.

Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:

$(window).on('load', function() { ... });