按顺序动态加载js, 可控版本, 有回调

load和onScriptLoad方法是直接从layerui的源码里粘贴出来修改了一下用的, 来源: https://gitee.com/sentsin/layui/blob/master/src/layui.js  

 

var version = 1;

function jsloader(arr, cb) {
    var head = document.getElementsByTagName('head')[0];

    var _load_index = 0;

    function onScriptLoad(node, e, url) {
        var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/
        if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
            head.removeChild(node);
            onCallback();
        }
    }

    function onCallback() {
        _load_index++;
        if (_load_index == arr.length) {
            cb();
        } else {
            load(arr[_load_index]);
        }
    }

    var isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]';

    function load(url) {
        var node = document.createElement('script');

        node.async = true;
        node.charset = 'utf-8';
        node.src = url + '?v=' + version;

        head.appendChild(node);
        if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) {
            node.attachEvent('onreadystatechange', function (e) {
                onScriptLoad(node, e, url);
            });
        } else {
            node.addEventListener('load', function (e) {
                onScriptLoad(node, e, url);
            }, false);
        }
    }

    load(arr[_load_index]);
}

 

 

使用方法:

//使用方式
jsloader(["js/1.js", "js/2.js", "js/3.js"], function () {
console.log('all complete'); });

1/2/3.js内容

//1.js
var a = 1;
console.log(1);

//2.js
var b = 1;
console.log('a:' + a + ' / ' + 2);


//3.js
var c = 1;
console.log('a:' + a + ' / ' + 'b:' + b + ' / ' + 3);

 

效果:

posted @ 2019-01-24 10:13    阅读(448)  评论(0编辑  收藏  举报