Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 349
newbie29 Avatar asked Feb 12 '12 14:02

newbie29


1 Answers

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();">  
like image 142
Biranchi Avatar answered Sep 22 '22 06:09

Biranchi