2011-05-16 101 views
1

我忙於一個項目,並且有一些額外的JavaScript文件需要在項目運行時加載。現在我已經創建了以下代碼:動態腳本加載

var script = _thisIframe.contentDocument.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'main.js?' + Math.random(); 

_thisIframe.contentDocument.body.appendChild(script); 

此代碼在Firefox,Safari,Chrome,Opera IE9和IE8中正常工作。但它好好嘗試一下在IE7 在這裏,我得到以下錯誤:當它的的createElement線創建

SCRIPT5007: Unable to get value of the property 'createElement': object is null or undefined

錯誤。

我搜索了這種類型的錯誤,但我沒有找到答案。

感謝

回答

1

contentDocument不支持IE7,或者更具體地說,你得到這個錯誤,因爲contentDocument不是_thisIframe,因此返回undefined,這當然沒有createElement()方法的屬性。

使用contentWindow.document支持IE7。

一個簡單的方法來獲得正確的屬性是利用了||邏輯運算符和short circuiting性質,以及在JavaScript的條件返回上次評估值(次數最多的truthy數)。

var doc = _thisIframe.contentDocument || _thisIframe.contentWindow.document; 
+0

哎呀。這是問題所在。謝謝! – jeroenjoosen 2011-05-16 12:10:55