Javascript – How to check if iframe is loaded or it has a content

iframejavascriptjquery

I have an iframe with id = "myIframe" and here my code to load it's content :

$('#myIframe').attr("src", "my_url");

The problem is sometimes it take too long for loading and sometimes it loaded very quickly. So I must to use "setTimeout" function :

setTimeout(function(){
   if (//something shows iframe is loaded or has content)
   {
       //my code
   }
   else
   {
       $('#myIframe').attr("src",""); //stop loading content
   }
},5000);

All I want to know is how to find out if an iFrame is loaded or it has content. Using iframe.contents().find() will not work. I can't use iframe.load(function(){}).

Best Answer

Try this.

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();">