關於動態載入js

來源:互聯網
上載者:User

標籤:

已知一個需要動態載入的js的檔案路徑數組,動態載入數組裡面所有的js檔案。

載入分兩種情況:

1. 並行載入,不管js的執行順序。

2. 串列載入,即一個一個載入,上一個載入完再載入下一個,直到最後。

 

動態載入js一般都是動態建立一個script,

解決第一種情況:

function loadExternalFile(src,parentElement,tagName){        var elem = document.createElement(tagName);        if(tagName===‘link‘){            elem.setAttribute(‘href‘,src);            elem.setAttribute(‘rel‘,‘stylesheet‘);        }else if(tagName===‘script‘){            elem.setAttribute(‘src‘,src);            elem.setAttribute(‘type‘,‘text/javascript‘);        }        parentElement.appendChild(elem);    }

解決第二種情況:

function loadScript(url, parentEle, tagName, callback){        var ele = document.createElement(tagName);        var typeProp = tagName===‘script‘?‘type‘:‘rel‘;        ele[typeProp] = tagName===‘script‘?‘text/javascript‘:‘stylesheet‘;        if (ele.readyState){  //IE            ele.onreadystatechange = function(){                if (ele.readyState == "loaded" ||                        ele.readyState == "complete"){                    ele.onreadystatechange = null;                    callback();                }            };        } else {  //Others            ele.onload = function(){                callback();            };        }        typeProp = tagName===‘script‘?‘src‘:‘href‘;        ele[typeProp] = url;        parentEle.appendChild(ele);    }

第一種情況用法非常簡單就不說了。

第二種用法其實也不難:

假設:scripts數組:[‘a.js‘,‘b.js‘,‘c.js‘]

var i=0;var n=scripts.length;loadScript(scripts[i],parentEle,‘script‘,loadScriptComplete);function loadScriptComplete(){     i++;     if(i<n){         loadScript(scripts[i],parentEle,‘script‘,loadScriptComplete);     }}

上面的兩種方法其實也適用於載入css檔案。

 

關於動態載入js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.