2013-06-04 21 views
0

我在Ajax調用oncomplete時向我的網站添加了一個JavaScript文件(使用appendChild)。之後,我試圖調用該文件中包含的函數。像這樣:檢查JavaScript是否在Ajax調用中加載?

// append the JS to the head 
document.getElementsByTagName('head')[0].appendChild(element); 

// call a function that is contained in the js file 
myFunction(); 

對myFunction的調用說「沒有定義myFunction()」。問題是,我怎麼知道它何時被定義?

謝謝!

+0

tes如果它不是未定義的可能? –

+0

http://stackoverflow.com/questions/6725272/dynamic-cross-browser-script-loading – Prinzhorn

+1

'typeof(myFunction)===「undefined」' – BrunoLM

回答

1

你可以做

if (myfunction != undefined) 
{ 
} 

此外,以確保它是你可以添加此

if(typeof (window.myFunction) == ‘function’) { 
+1

你的第一個例子會在myfunction函數未定義時拋出一個錯誤。第二個是更好的:-) – tborychowski

1

您可以使用onload找出它是完成時的功能。

var s = document.createElement('script'); 
s.onreadystatechange = s.onload = function() { 
    var state = s.readyState; 

    if (!callback.done && (!state || /loaded|complete/.test(state))) { 
     // done! 
    } 
}; 
s.src = "myurl/myscript.js"; 
document.getElementsByTagName('head')[0].appendChild(s); 
+0

一個字:** IE **:http://stackoverflow.com/questions/6725272/dynamic-cross-browser-script-loading – Prinzhorn

+0

是的,真的,更新爲... – Gabe

+0

它不會工作! – Givi

相關問題