DIV CSS 佈局教程網

跨 iframe 動態載入 JS 與 CSS
編輯:JavaScript綜合知識     

iframe 結構中,子框架需要動態載入資源到另一個子框架時,關鍵是取得目標框架的 document,再往裡面塞節點。這裡有兩種做法,同步與非同步的差異很重要。

結構前提

frame0(父)→ frame2(子)、frame3(子)。frame2 觸發事件,動態往 frame3 載入 js、css 與 DOM 元素。

同層框架之間可以互相存取,路徑是「子 → 父 → 子」:

parent.parentFrame("要呼叫的另一個子框架的方法");

前提是全部同源。跨來源時,這種存取一律被瀏覽器阻擋。

方法一:jQuery append()

速度快、同步執行,但需要目標框架中已載入 jQuery:

var oBody = document.getElementById("frame3_id").contentWindow.$("body");
var str = "<div>...</div>";

var scriptTag = document.getElementById("frame3_id").contentWindow
                  .document.getElementById("pop");
if (!scriptTag) {
  oBody.append(str);
}

var oScript = document.createElement("script");
oScript.id = "oScript1";
oScript.type = "text/javascript";
oScript.src = "/test.js";

var oTag1 = document.getElementById("frame3_id").contentWindow
              .document.getElementById("oScript1");
if (!oTag1) {
  oBody.append(oScript);
}

document.getElementById("frame3_id").contentWindow.test();   // 呼叫 frame3 中的方法

注意 createElement 是用「目前文件」的 document 建立的,卻附加到另一個文件上。多數情況能動,但嚴格來說應該用目標文件的 document 來建立,比較保險。

方法二:原生 appendChild()

較慢、非同步,必須等到載入完成才能呼叫其中的方法:

var targetWin = document.getElementById("frame3_id").contentWindow;
var targetDoc = targetWin.document;

var str = "<div>...</div>";
var popDiv = targetDoc.createElement('div');
popDiv.id = "pop";
popDiv.innerHTML = str;

var oBody = targetDoc.getElementsByTagName("body")[0];
var oHead = targetDoc.getElementsByTagName("head");
oHead = (oHead && oHead.length) ? oHead[0] : oBody;

if (!targetDoc.getElementById("pop")) {
  oBody.appendChild(popDiv);
}

var oScript = targetDoc.createElement("script");       // css 用 link 標籤,做法相同
oScript.id = "oScript1";
oScript.type = "text/javascript";
oScript.src = "/test.js";

if (!targetDoc.getElementById("oScript1")) {
  oHead.appendChild(oScript);
}

oScript.onload = oScript.onreadystatechange = function () {
  if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded") {
    targetWin.test();                                  // test() 定義在載入的 js 中
  } else {
    console.info("can not load the oScript2.js file");
  }
};

為什麼要檢查 readyState

onreadystatechange 是 IE 專屬的事件,readyState 會經歷 loading、complete、loaded 等狀態,同一個檔案可能觸發多次。標準瀏覽器只用 onload,兩者並掛是為了跨瀏覽器相容。今天寫 onload 就夠了。

實務上的關鍵差異

同步與非同步是這兩種做法最實質的分別。append() 之後立刻呼叫 frame3 裡的 test(),是因為 jQuery 在插入 script 時會同步處理(部分版本會用 eval 立即執行)。而 appendChild 插入的 script 一律是非同步載入,必須等 onload。若照抄 append 版本的寫法去用 appendChild,就會得到「test is not defined」。

重複載入:兩個版本都用 getElementById 檢查是否已存在,避免重複插入。這個檢查是必要的,否則每次觸發都會多一個 script 標籤。

css 的做法完全相同,只是把 script 換成 link,並設定 rel="stylesheet" 與 href。link 的 onload 支援度較差,實務上常改用 setTimeout 輪詢或直接假設已載入。

建議

跨 iframe 動態注入資源是很舊的技巧,主要出現在後台系統的插件機制裡。新專案請直接用 ES Module 的 import(),它會自動處理去重、快取與載入順序:

const mod = await import('/module.js');
mod.init();
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved