Dynamically load a JavaScript file

后端 未结 28 3045
说谎
说谎 2020-11-22 06:56

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when \'initialized\' the component will dynamical

28条回答
  •  醉酒成梦
    2020-11-22 07:45

    If you want a SYNC script loading, you need to add script text directly to HTML HEAD tag. Adding it as will trigger an ASYNC load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):

    /*sample requires an additional method for array prototype:*/
    
    if (Array.prototype.contains === undefined) {
    Array.prototype.contains = function (obj) {
        var i = this.length;
        while (i--) { if (this[i] === obj) return true; }
        return false;
    };
    };
    
    /*define object that will wrap our logic*/
    var ScriptLoader = {
    LoadedFiles: [],
    
    LoadFile: function (url) {
        var self = this;
        if (this.LoadedFiles.contains(url)) return;
    
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    self.LoadedFiles.push(url);
                    self.AddScript(xhr.responseText);
                } else {
                    if (console) console.error(xhr.statusText);
                }
            }
        };
        xhr.open("GET", url, false);/*last parameter defines if call is async or not*/
        xhr.send(null);
    },
    
    AddScript: function (code) {
        var oNew = document.createElement("script");
        oNew.type = "text/javascript";
        oNew.textContent = code;
        document.getElementsByTagName("head")[0].appendChild(oNew);
    }
    };
    
    /*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/
    
    ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
    ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
    /*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id "tb1"*/
    $(function () { alert($('#tb1').val()); });
    

提交回复
热议问题