判断iframe是否加载完成的完美方法

  作者:bea

代码如下: var iframe = document.createElement("iframe"); iframe.src = "http://"; if (!/*@cc_on!@*/0) { //if not IE iframe.onload = function(){ alert("Local iframe is now loaded."); }; } else { iframe.onreadystatechange = function(){

代码如下:


var iframe = document.createElement("iframe");
iframe.src = "http://";

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



最近, Nicholas C. Zakas 文章《Iframes, onload, and document.domain》的评论中 Christopher 提供了一个新的判断方法(很完美):

代码如下:


var iframe = document.createElement("iframe");
iframe.src = "http://";

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




几点补充说明:


IE 支持 iframe 的 onload 事件,不过是隐形的,需要通过 attachEvent 来注册。
第二种方法比第一种方法更完美,因为 readystatechange 事件相对于 load 事件有一些潜在的问题。



有用  |  无用

猜你喜欢