异步加载js代码

异步加载js代码

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);

  

经过艺术加工后的代码如下:

/**
 * 
 * 定义一个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()});

  

原文地址:https://www.cnblogs.com/guxingzhe/p/6592977.html