DIV CSS 佈局教程網

動態載入外部 JS 與 iframe,並在載入完成後執行的回呼寫法
編輯:關於JavaScript     

回呼(callback)指的是:某個方法執行完畢後,自動接著執行另一個指定的方法。在 JavaScript 的世界裡,最典型的兩個應用就是「動態載入腳本」與「動態載入 iframe」——兩者都需要等到載入真正完成,才能安全地動用其中的資源。

一、動態載入 JS 檔案,完成後回呼

<script>
/* 動態載入腳本庫 */
function include_js(file) {
  var _doc = document.getElementsByTagName('head')[0];
  var js = document.createElement('script');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', file);
  _doc.appendChild(js);

  if (!/*@cc_on!@*/0) {
    // 非 IE:Firefox2/3、Safari3.1+、Opera9.6+ 支援 onload
    js.onload = function () {
      // …你的程式邏輯
    };
  } else {
    // IE6、IE7:只能依賴 onreadystatechange
    js.onreadystatechange = function () {
      if (js.readyState == 'loaded' || js.readyState == 'complete') {
        // …你的程式邏輯
        // 例如載入 jQuery 後直接呼叫它的方法
        $("#div1").html("ok");
      }
    };
  }
  return false;
}

// 執行
include_js('https://img1.c2cedu.com/Scripts/jquery/jquery-1.4.2.min.js');
</script>

這裡的 /*@cc_on!@*/0 是 IE 條件式編譯註解,用來判斷是否為 IE,比解析 user-agent 更可靠。另外要特別注意:事件必須在 appendChild 之前綁定,否則腳本被快取而瞬間載完時,回呼可能永遠不會觸發。

二、動態載入 iframe,完成後回呼

<script>
var iframe = document.createElement("iframe");
iframe.src = "https://www.example.com";

if (iframe.attachEvent) {
  // 舊版 IE
  iframe.attachEvent("onload", function () {
    // …你的程式邏輯
  });
} else {
  iframe.onload = function () {
    // …你的程式邏輯
  };
}

document.body.appendChild(iframe);
</script>

這裡的順序與上面同理:先掛事件、設定 src,最後才 appendChild。實務上更常見的寫法是先 appendChild 再指定 src,這麼做的好處是 iframe 一定進入 DOM 之後才開始載入,事件絕不會漏接。

一個更通用的封裝

把兩種情況抽成一個函數,判斷邏輯集中在一處:

function onLoad(el, callback) {
  if (!el) return;
  if (el.readyState) {
    // 走 onreadystatechange 的多為 script / 舊 IE iframe
    el.readyState === "complete" || el.readyState === "loaded"
      ? callback()
      : (el.onreadystatechange = function () {
          if (el.readyState === "complete" || el.readyState === "loaded") callback();
        });
  } else {
    el.onload = callback;   // 標準寫法
  }
}

最後提醒:如果你只是想載入外部腳本,今天更推薦動態建立 <script> 並搭配 onload(標準瀏覽器一律支援),或使用 fetch / dynamic import()。上面這套 readyState 判斷主要是歷史相容包袱。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved