The perfect way to judge whether the iframe is loaded under js

http://www.jb51.net/article/25128.htm

Generally speaking, judging whether the iframe is loaded is actually the same as judging whether the JavaScript file is loaded.

The approach taken is very similar:

Copy the code The code is as follows:

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

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


Recently, Christopher in the comments of Nicholas C. Zakas ' article "Iframes, onload, and document.domain" provided a new judgment method (perfect):

Copy the code The code is as follows:

var iframe = document.createElement("iframe");
iframe.src = "http://sc.jb51.net";
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);


A few additional notes:

IE supports the onload event of iframe, but it is invisible and needs to be registered through attachEvent.
The second method is more perfect than the first because the readystatechange event has some potential problems with the load event.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325014584&siteId=291194637