1. 程式人生 > >動態新增js檔案

動態新增js檔案

function loadScript(url, callback, dataName, dataDeps){
       var script = document.createElement('script');
       script.type = 'text/javascript';
       if(dataName){
           script.setAttribute("data-name",dataName);
       }
       if(dataDeps){
           script.setAttribute("data-deps",dataDeps);
       }
       if
(script.readyState){//IE script.onreadystatechange = function(){ if(script.readyState == 'loaded' || script.readyState == 'complete'){ script.onreadystatechange = null; callback() } } }else{//Other script.onload = function
(){
callback(); } } script.src = url; document.getElementsByTagName('head')[0].appendChild(script); }

當頁面中動態載入多個有關聯的JavaScript檔案時,我們可以將其串聯起來,保證順序。

loadScript('file1.js',function(){
    loadScript('file2.js',function(){
        ...
    });
});