Home > Article > Web Front-end > js如何判断 iframe 是否完全加载
<code class="language-javascript">var iframe = document.createElement("iframe"); iframe.src = "http://www.manongjc.com"; if (!/*@cc_on!@*/0) { //if not IE iframe.onload = function(){ alert("Local iframe is now loaded."); }; } else { iframe.onreadystatechange = function(){ if (iframe.readyState == "complete"){ alert("Local iframe is now loaded."); } }; } document.body.appendChild(iframe); </code>
最近, Nicholas C. Zakas 文章《Iframes, onload, and document.domain》的评论中 Christopher 提供了一个新的判断方法(很完美):
<code class="language-javascript">var iframe = document.createElement("iframe"); iframe.src = "http://manongjc.com"; if (iframe.attachEvent){ iframe.attachEvent("onload", function(){ alert("Local iframe is now loaded."); }); } else { iframe.onload = function(){ alert("Local iframe is now loaded."); }; } document.body.appendChild(iframe); </code>
几点补充说明: