[ Util.load([
["/misc/js/content.js", function() { // 單個回調 }], ["/misc/js/comment.js"], ["/misc/js/home.js"] ], function() { // 全域回調 }); ] [
var Util = {
/** * 全域js列表 */ scripts: {}, head: document.head || document.getElementsByTagName("head")[0] || document.documentElement, /** * 非同步載入js檔案 */ load: function(queue, callback) { var self = this, queued = queue.length; for (var i = 0, l = queue.length; i < l; i++) { var elem; elem = document.createElement("script"); elem.setAttribute("type", "text/javascript"); elem.setAttribute("async", "async"); elem.setAttribute("src", queue[i][0]); // 檔案還沒有處理過 if (typeof this.scripts[elem.src] === "undefined") { // 使onload取得正確elem和index (function(elem, index) { elem.onload = elem.onreadystatechange = function() { if (! elem.readyState || /loaded|complete/.test(elem.readyState)) { queued--; // 解決IE記憶體泄露 elem.onload = elem.onreadystatechange = null; // 釋放引用 elem = null; // 調用callback queue[index][1] && queue[index][1](); // 隊列全部載入,調用最終callback if (queued === 0) { callback && callback(); } } }; })(elem, i); } // 已處理,調用callback else { queued--; queue[i][1] && queue[i][1](); } this.head.appendChild(elem); // 隊列全部載入,調用最終callback if (queued === 0) { callback && callback(); } } } }; ]
|