Dynamically loading JavaScript synchronously

后端 未结 18 2334
小蘑菇
小蘑菇 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:45

    The most Node.js-like implementation I could come up with was able to load JS files synchonously, and use them as objects/modules

    var scriptCache = [];
    var paths = [];
    function Import(path)
    {
        var index = 0;
        if((index = paths.indexOf(path)) != -1) //If we already imported this module
        {
            return scriptCache [index];
        }
    
        var request, script, source;
        var fullPath = window.location.protocol + '//' + window.location.host + '/' + path;
    
        request = new XMLHttpRequest();
        request.open('GET', fullPath, false);
        request.send();
    
        source = request.responseText;
    
        var module = (function concealedEval() {
            eval(source);
            return exports;
        })();
    
        scriptCache.push(module);
        paths.push(path);
    
        return module;
    }
    

    An example source (addobjects.js):

    function AddTwoObjects(a, b)
    {
        return a + b;
    }
    
    this.exports = AddTwoObjects;
    

    And use it like this:

    var AddTwoObjects = Import('addobjects.js');
    alert(AddTwoObjects(3, 4)); //7
    //or even like this:
    alert(Import('addobjects.js')(3, 4)); //7
    

提交回复
热议问题