JavaScript:异步下载js,当下载失败时,如何调用错误函数

时间:2013-03-05 08:18:00

标签: javascript

常见的异步下载js功能如下。

但是当下载失败时,如何调用错误函数。

这个函数将是:function loadScript(url,callback,errcb)。

function loadScript(url, callback){ 
    var script = document.createElement("script") 
    script.type = "text/javascript"; 
    if (script.readyState){ //IE 
        script.onreadystatechange = function(){ 
            if (script.readyState == "loaded" || script.readyState == "complete"){ 
                script.onreadystatechange = null; 
                callback(); 
            } 
         }; 
    } else { //Others: Firefox, Safari, Chrome, and Opera 
        script.onload = function(){ 
            callback(); 
        }; 
    } 
    script.src = url; 
    document.body.appendChild(script); 
} 

0 个答案:

没有答案