如何检查iframe是否已加载或是否包含内容?

我有一个id =“ myIframe”的iframe,这里是我加载其内容的代码:


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

问题是有时加载时间太长,有时加载速度非常快。所以我必须使用“ setTimeout”函数:


setTimeout(function(){

   if (//something shows iframe is loaded or has content)

   {

       //my code

   }

   else

   {

       $('#myIframe').attr("src",""); //stop loading content

   }

},5000);

我唯一想知道的是如何确定是否已加载iFrame或是否包含内容。使用iframe.contents().find()将不起作用。我不能用iframe.load(function(){})。


跃然一笑
浏览 921回答 3
3回答

沧海一幻觉

尝试这个。<script>function checkIframeLoaded() {&nbsp; &nbsp; // Get a handle to the iframe element&nbsp; &nbsp; var iframe = document.getElementById('i_frame');&nbsp; &nbsp; var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;&nbsp; &nbsp; // Check if loading is complete&nbsp; &nbsp; if (&nbsp; iframeDoc.readyState&nbsp; == 'complete' ) {&nbsp; &nbsp; &nbsp; &nbsp; //iframe.contentWindow.alert("Hello");&nbsp; &nbsp; &nbsp; &nbsp; iframe.contentWindow.onload = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("I am loaded");&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; // The loading is complete, call the function we want executed once the iframe is loaded&nbsp; &nbsp; &nbsp; &nbsp; afterLoading();&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; // If we are here, it is not loaded. Set things up so we check&nbsp; &nbsp;the status again in 100 milliseconds&nbsp; &nbsp; window.setTimeout(checkIframeLoaded, 100);}function afterLoading(){&nbsp; &nbsp; alert("I am here");}</script><body onload="checkIframeLoaded();">&nbsp;

蝴蝶刀刀

请使用:$('#myIframe').on('load', function(){&nbsp; &nbsp; //your code (will be called once iframe is done loading)});随着标准的更改,更新了我的答案。
打开App,查看更多内容
随时随地看视频慕课网APP