2013-04-16 31 views
2

我嘗試在https://stackoverflow.com/a/950146/151453處提供的代碼,並且我成功驗證了我可以從t1.js加載我的t2.js。但是,t2.js完成加載回叫僅適用於Chrome(v26),Firefox(v17)和IE10,,但不適用於Microsoft IE8(Windows 7)如何使用IE8包含js js,使用IE8

IE8上的症狀是:從不調用回調start_deco()

我怎樣才能在IE8中實現相同的結果?謝謝。

====代碼如下====

t1.html:

<html> 
<head></head> 

<body> 
Hello! 

<script src="t1.js"></script> 

</body> 
</html> 

t1.js:

// loadScript function provided by https://stackoverflow.com/a/950146/151453 
function loadScript(url, callback) 
{ 
    // adding the script tag to the head as suggested before 
    var head = document.getElementsByTagName('head')[0]; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = url; 

    // then bind the event to the callback function 
    // there are several events for cross browser compatibility 
    //script.onreadystatechange = callback; // chj: !!! 
    script.onload = callback; 

    // fire the loading 
    head.appendChild(script); 
} 

function start_deco() 
{ 
    alert('Done t2.js.'); 
    loadScript('t3.js.'); 
} 

loadScript('t2.js', start_deco) // wish to load jquery.js etc 

t2.js:

console.log('Loading t2.js...') 

t3.js:

console.log('Loading t3.js...') 

enter image description here

============== UPDATE1 =================

在IE8,如果我在loadScript()中啓用script.onreadystatechange = callback;,警告框會彈出,但是,調用loadScript('t3.js.');失敗,並且該行上出現「未執行錯誤」,導致t3.js無法加載。如下圖:

enter image description here

+1

您可能遇到安全問題,從IE8中的file:// URL運行。嘗試從Web服務器運行相同的代碼並查看它是否可用。 –

+0

你在IE8中收到任何JavaScript錯誤嗎? (右下方是紅色的X) – wanovak

+0

@MikeMcCaughan是對的 - 您是否安裝了IE開發工具或Firebug lite?看看控制檯,看看有什麼報告。 – CherryFlavourPez

回答

2

哦,我明白了。是我的錯!由https://stackoverflow.com/a/950146/151453提供的loadScript()在IE8和Firefox,Chrome上完全可行。

而且,爲了使它在IE9 +中工作,我必須遵循以下微軟建議:http://msdn.microsoft.com/en-us/library/ie/hh180173(v=vs.85).aspx

這是我的錯,註釋掉script.onreadystatechange = callback;聲明。

我的IE8控制檯上顯示的「未執行」錯誤是由於在調用loadScript('t3.js.');時缺少callback參數。

因此,要解決這個問題,我要補充一行loadScript(),最後的結果是:

​​

驗證了IE8,IE9,火狐17時,Chrome 27。

+0

我有一個類似的問題,對於內聯js我使用createElement('腳本'),但對於跨瀏覽器外部js我只是這樣做:document.write('

0

我知道這是不是從JS,但是這是一種選擇?

<html> 
    <head></head> 
    <body> 
     Hello! 

     <script src="t1.js"></script> 
     <!--[if IE 8]> 
      <script src="t2.js"></script> 
     <![endif]--> 
    </body> 
</html> 
+0

對不起,我需要從另一個js加載一個js,而不是html,以避免靜態html維護的噩夢。 –

1

IE8及以上處理script對象有點不同 - 他們不暴露一個onLoad事件,而是一個onReadyStateChange事件。您可以看看Mootools的Asset.javascript函數,其中https://github.com/mootools/mootools-more/blob/master/Source/Utilities/Assets.js就是一個很好的例子。你主要是尋找這部分:

if (!script.addEventListener){ 
    script.addEvent('readystatechange', function(){ 
    if (['loaded', 'complete'].contains(this.readyState)) load.call(this); 
    }); 
} else { 
    script.addEvent('load', load); 
} 

應該課程,這樣的情況是首要原因,總是用喜歡Moot或jQuery的圖書館之一指出,確切地避免這樣的問題。