動態載入Javascript增強版本

來源:互聯網
上載者:User

我們經常使用動態載入Javascript,寫個函數很容易現實,之前也寫過一個函數,不過當載入多個JS時,只能根據瀏覽器返回的順序來先後載入,這肯定不是我們想要的,現在使用了一下技巧,當載入多個JS時,能按照我們的順序載入:

/*    Name:動態載入JS    Author:kingwell Leng    Date : 2013/4/21    E-mail: jinhua.leng##gmail.com*/function getScript(obj, callback) {    var arr = obj,    timeout,    str = typeof obj === 'string';    function add() {        var script = document.createElement("script");            header = document.getElementsByTagName("head")[0];        script.src = str ? obj : arr[0];        script.type = "text/javascript";        if (str) {            if (script.readyState) {                script.onreadystatechange = function () {                    if (script.readyState === 'loaded' || script.readyState === 'complete') {                        script.onreadystatechange = null;                        callback && callback();                    }                };            } else {                script.onload = function () {                    callback && callback();                };            }        } else {            if (arr.length >= 1) {                if (script.readyState) {                    script.onreadystatechange = function () {                        if (script.readyState === 'loaded' || script.readyState === 'complete') {                            script.onreadystatechange = null;                            arr.shift();                            timeout = setTimeout(add, 1);                        }                    };                } else {                    script.onload = function () {                        arr.shift();                        timeout = setTimeout(add, 1);                    };                }            } else {                clearTimeout(timeout);                callback && callback();            }        }        header.appendChild(script);    }    add();}

 

調用:

getScript(['http://code.jquery.com/jquery-1.9.1.min.js','js1.js', 'js2.js', 'js3.js', 'js4.js'], function () {alert('我是按順序載入啦');});

 現在是按照我們寫代碼的順序載入啦...

 

 

 

 

 

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.