我們經常使用動態載入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('我是按順序載入啦');});
現在是按照我們寫代碼的順序載入啦...