jQuery iframe load() event?

JavascriptAjaxJqueryIframe

Javascript Problem Overview


Does anyone know if there is such a thing?

I have a iframe that's being inserted with $.ajax() and I want to do some stuff after the contents from the iframe are completely loaded:

....
 success: function(html){  // <-- html is the IFRAME (#theiframe)
          $(this).html(html);   // $(this) is the container element
          $(this).show();
          $('#theiframe').load(function(){
             alert('loaded!');
          } 
....

it works, but I see the IFRAME is loaded twice (the alert also shows twice).

Javascript Solutions


Solution 1 - Javascript

use iframe onload event

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

Solution 2 - Javascript

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();
}

Solution 3 - Javascript

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() { ... });

Solution 4 - Javascript

That's the same behavior I've seen: iframe's load() will fire first on an empty iframe, then the second time when your page is loaded.

Edit: Hmm, interesting. You could increment a counter in your event handler, and a) ignore the first load event, or b) ignore any duplicate load event.

Solution 5 - Javascript

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

	jQuery(document).ready(function($) {

		$(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

	});

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

Solution 6 - Javascript

You may use the jquery's Contents method to get the content of the iframe.

Solution 7 - Javascript

If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.

//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
        cookieValue = $.cookie('iframeToken');	
        if (cookieValue == token)
        {
            window.clearInterval(iframeLoadCheckTimer );
            $.cookie('iframeToken', null, {
                expires: 1, 
                path: '/'
         });
        }
 }, 1000);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - Javascriptm-khonsariView Answer on Stackoverflow
Solution 2 - JavascriptTim DownView Answer on Stackoverflow
Solution 3 - JavascriptOliverView Answer on Stackoverflow
Solution 4 - JavascriptPiskvor left the buildingView Answer on Stackoverflow
Solution 5 - JavascriptJérome ObbietView Answer on Stackoverflow
Solution 6 - JavascriptsuhairView Answer on Stackoverflow
Solution 7 - JavascriptBahadır BirsözView Answer on Stackoverflow