動態建立 iframe 之後,往往需要知道它「什麼時候載入好了」,才能接著做後續動作,例如調整高度、注入腳本或讀取內容。麻煩的是各家瀏覽器的事件名稱並不統一,因此需要做能力偵測。
IE 系(包含舊版 Edge 相容模式)走的是 onreadystatechange,透過 readyState 判斷是否來到 loaded 或 complete;標準瀏覽器則直接用 onload。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body>
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
var iframe = document.createElement("iframe");
iframe.src = "https://www.baidu.com/";
if (isIE) {
iframe.onreadystatechange = function(){
if (iframe.readyState == "loaded" || iframe.readyState == "complete"){
alert("loaded");
}
};
} else {
iframe.onload = function(){
alert("loaded");
};
}
document.body.appendChild(iframe);
</script>
</body>
</html>
相對於用 userAgent 字串比對,直接偵測 attachEvent 這個方法是否存在,是更可靠 also 更容易維護的做法——不必去猜版本號。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body>
<script type="text/javascript">
var iframe = document.createElement("iframe");
iframe.src = "https://www.baidu.com/";
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
alert("loaded");
});
} else {
iframe.onload = function(){
alert("loaded");
};
}
document.body.appendChild(iframe);
</script>
</body>
</html>
事件綁定最好在把 iframe 掛進 DOM 之前完成,或者至少在設定 src 之前掛好,否則快取命中時可能來不及攔到載入完成的通知。
另外,若 iframe 指向的是跨來源網址,載入完成後你依然無法讀取它內部的文件內容,這是瀏覽器同源政策所限,與載入是否完成無關。