异步加载JS时的加载顺序问题

通过document.createElement('script')方式加载JS文件时,文件是动态加载进来的,没法控制加载的顺序。下面是简单的解决办法,更好的解决办法是使用AMD或CMD方式来管理模块,比如require.js或sea.js


var requireFile = function (file, callback) {
    callback = callback || function () {};
    var filenode;
    var jsfile_extension = /(.js)$/i;
    var cssfile_extension = /(.css)$/i;

    if (jsfile_extension.test(file)) {
        filenode = document.createElement('script');
        filenode.src = file;
        // IE
        filenode.onreadystatechange = function () {
            if (filenode.readyState === 'loaded' || filenode.readyState === 'complete') {
                filenode.onreadystatechange = null;
                callback();
            }
        };
        // others
        filenode.onload = function () {
            callback();
        };
        document.head.appendChild(filenode);
    } else if (cssfile_extension.test(file)) {
        filenode = document.createElement('link');
        filenode.rel = 'stylesheet';
        filenode.type = 'text/css';
        filenode.href = file;
        document.head.appendChild(filenode);
        callback();
    } else {
        console.log("Unknown file type to load.")
    }
};

var loaded = [];

var requireFiles = function () {
    var index = 0;

    return function (files, callback) {
        callback = callback || function () {};
        index += 1;
        f = files[index - 1];


        //console.log(loaded);

        if(loaded.indexOf(f) != -1) {
            //console.log("pass:",f);
            callBackCounter();
        }else{
            requireFile(f, callBackCounter);
            loaded.push(f);
        }

        function callBackCounter() {
            if (index === files.length) {
                index = 0;
                callback();
            } else {
                requireFiles(files, callback);
            }
        };
    };
}();

你可能感兴趣的:(异步加载JS时的加载顺序问题)