異步加載js代碼javascript
function addTag(name, attributes, sync) { var el = document.createElement(name),attrName; for (attrName in attributes) { el.setAttribute(attrName, attributes[attrName]); } sync ? document.write(outerHTML(el)) : appendHead(el); } // 插入頭部 function appendHead(node) { var headEl = document.getElementsByTagName("head"); headEl[0].appendChild(node) } // 將script轉換一次,直接插入會出現無效效果 function outerHTML(node) { // if IE, Chrome take the internal method otherwise build one return node.outerHTML || (function (n) { var div = document.createElement('div'), h; div.appendChild(n); h = div.innerHTML; div = null; return h; })(node); } addTag('script', {src: 'ui/bootstrap-table/bootstrap-table.min.js?v='+Date.now()}, true); addTag('script', {src: 'ui/bootstrap-table/locale/bootstrap-table-zh-CN.min.js?v='+Date.now()}, true);
通過藝術加工後的代碼以下:html
/** * * 定義一個js異步加載方法 * 加載框架所需js和配置文件 * */ (function(w) { var Loader = function(){}; Loader.prototype.load = function(name, attributes, sync) { // 沒定義默認爲true if (typeof sync === 'undefined') sync = true; var el = document.createElement(name),attrName; for (attrName in attributes) { el.setAttribute(attrName, attributes[attrName]); } sync ? document.write(this.outerHTML(el)) : this.appendHead(el); } // 插入頭部 Loader.prototype.appendHead = function(node) { var headEl = document.getElementsByTagName("head"); headEl[0].appendChild(node) } // 將script轉換一次,直接插入會出現無效效果 Loader.prototype.outerHTML = function(node) { // if IE, Chrome take the internal method otherwise build one return node.outerHTML || (function (n) { var div = document.createElement('div'), h; div.appendChild(n); h = div.innerHTML; div = null; return h; })(node); } w.loader = new Loader(); }(window)) // 時間戳 var load = function() {return "?_load=" + new Date().getTime();}; // 加載框架所需js loader.load('script', {src: 'js/corejs/jquery-1.11.2.min.js'+load()}); loader.load('script', {src: 'js/corejs/bootstrap.min.js'+load()}); loader.load('script', {src: 'js/corejs/angular/angular.min.js'+load()}); loader.load('script', {src: 'ui/angular-ui-router/angular-ui-router.js'+load()}); loader.load('script', {src: 'ui/ocLazyLoad.1.0.9.js'+load()}); loader.load('script', {src: 'js/comjs/config.js'+load()}); loader.load('script', {src: 'js/comjs/frame_commonly.js'+load()});