萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

判斷 iframe 載入完成的最佳實踐:attachEvent + onload 統一寫法

傳統做法需分別處理 IE 的 onreadystatechange 與標準瀏覽器的 onload,但 Nicholas C. Zakas 文章評論中 Christopher 提供了更完美的統一寫法:

推薦寫法

var iframe = document.createElement('iframe');
iframe.src = 'https://www.planabc.net';

if (iframe.attachEvent) {
  // IE:需用 attachEvent 註冊隱形 onload
  iframe.attachEvent('onload', function() {
    alert('Local iframe is now loaded.');
  });
} else {
  // 標準瀏覽器
  iframe.onload = function() {
    alert('Local iframe is now loaded.');
  };
}

document.body.appendChild(iframe);

為何優於傳統 readyState 判斷?

  1. IE 支援 iframe onload,只是隱形,需用 attachEvent 註冊。
  2. readystatechange 相對 load 事件存在潛在問題(如多次觸發、時機不準)。
  3. 統一用 onload 語義更清晰,程式碼更簡潔。

此法已成為判斷 iframe 載入完成的標準最佳實踐。

copyright © 萬盛學電腦網 all rights reserved