複習富文本編輯器的製作原理時,我把先前寫過的程式碼跑了一遍,卻發現一個棘手的問題:程式會拋出「找不到物件」的異常。以下還原整個排查過程與背後的原理。
var ifr = document.createElement('iframe');
ifr.width = 300;
ifr.height = 300;
var idoc = ifr.contentDocument || ifr.contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('<html><head></head><body></body></html>');
document.body.appendChild(ifr);
先上網確認取得 document 的寫法並沒有錯;接著懷疑是 Chrome 的問題,換到 Firefox 測試,結果一樣。既然兩個瀏覽器都相同,那問題一定出在自己的程式碼上。比對網路上的寫法後,發現 appendChild 的位置放得太後面,於是把它提前到取得 document 之前:
var ifr = document.createElement('iframe');
ifr.width = 300;
ifr.height = 300;
document.body.appendChild(ifr); // 先加入 DOM
var idoc = ifr.contentDocument || ifr.contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('<html><head><style>body{margin:3px;}</style></head><body></body></html>');
改完之後,一切運行順利。
其實原理很簡單:iframe 內部包含的是另一份文件,而這份文件必須先被「初始化」,才會擁有一個 document 物件。如果沒有把 iframe 元素加入 DOM 樹,內部的文件就不會初始化,此時 ifr.contentDocument 的值為 null,自然無法後續操作。
順著這條線索檢查其他元素會發現:一般元素節點只要一經建立,無論是否加入 DOM 樹,都會擁有自己的屬性與方法。由此看來,在眾多元素節點中,iframe 算是相當特殊的一個——它的文件初始化必須等到掛載進 DOM 之後才會發生。