Dynamically loading JavaScript synchronously

后端 未结 18 2335
小蘑菇
小蘑菇 2020-11-27 13:55

I\'m using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in t

18条回答
  •  天涯浪人
    2020-11-27 14:56

    This is the code that I'm using for multiple file load in my app.

    Utilities.require = 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.")
        }
    };
    
    Utilities.requireFiles = function () {
        var index = 0;
        return function (files, callback) {
            index += 1;
            Utilities.require(files[index - 1], callBackCounter);
    
            function callBackCounter() {
                if (index === files.length) {
                    index = 0;
                    callback();
                } else {
                    Utilities.requireFiles(files, callback);
                }
            };
        };
    }();
    

    And this utilities can be used by

    Utilities.requireFiles(["url1", "url2",....], function(){
        //Call the init function in the loaded file.
        })
    

提交回复
热议问题