2010-12-01 69 views
6

我已經做了一個js函數,在我的html中包含另一個javascript。我需要確保使用該函數加載的腳本已完成處理,然後僅在原始腳本中進一步移動。如何在特定的JS加載後運行javascript函數?

function loadBackupScript(){ 
    var script = document.createElement('script'); 
    script.src = 'http://www.geoplugin.net/javascript.gp'; 
    script.type = 'text/javascript'; 
    var head = document.getElementsByTagName("head")[0]; 
    head.appendChild(script); 
} 

我需要知道該腳本已經加載以使用其功能。我怎麼做?

回答

8
function loadBackupScript(callback) { 
    var script; 
    if (typeof callback !== 'function') { 
     throw new Error('Not a valid callback'); 
    } 
    script = document.createElement('script'); 
    script.onload = callback; 
    script.src = 'http://www.geoplugin.net/javascript.gp'; 
    document.head.appendChild(script); 
} 

loadBackupScript(function() { alert('loaded'); }); 
2

添加到您的函數:

// all cool browsers 
script.onload = doSomething; 
// IE 6 & 7 
script.onreadystatechange = function() { 
if (this.readyState == 'complete') { 
    doSomething(); 
} 

如果你不相信這些事件,你也可以使用的setTimeout()來檢查該功能的存在。 在這方面的一個很好的文章可以在這裏找到:

http://www.ejeliot.com/blog/109

1

我會建議使用LABJs這一點。

使用它,你可以做到這一點

$LAB 
.script("framework.js") 
.wait(function(){ 
    //called when framework.js is loaded 
}) 
.script("init.js") 
.wait(function(){ 
    //called when init.js is loaded 
}); 

這是跨瀏覽器的,並且往往比硬編碼的腳本標記到你的HTML更有效,由於它的方式支持並行下載。

您可以閱讀更多關於此here