Dynamically load a JavaScript file

后端 未结 28 3374
说谎
说谎 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:41

    I have tweaked some of the above post with working example. Here we can give css and js in same array also.

    $(document).ready(function(){
    
    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 jsScriptCssLoader = {
    
    jsExpr : new RegExp( "js$", "i" ),
    cssExpr : new RegExp( "css$", "i" ),
    loadedFiles: [],
    
    loadFile: function (cssJsFileArray) {
        var self = this;
        // remove duplicates with in array
        cssJsFileArray.filter((item,index)=>cssJsFileArray.indexOf(item)==index)
        var loadedFileArray = this.loadedFiles;
        $.each(cssJsFileArray, function( index, url ) {
                // if multiple arrays are loaded the check the uniqueness
                if (loadedFileArray.contains(url)) return;
                if( self.jsExpr.test( url ) ){
                    $.get(url, function(data) {
                        self.addScript(data);
                    });
    
                }else if( self.cssExpr.test( url ) ){
                    $.get(url, function(data) {
                        self.addCss(data);
                    });
                }
    
                self.loadedFiles.push(url);
        });
    
        // don't load twice accross different arrays
    
    },
    addScript: function (code) {
        var oNew = document.createElement("script");
        oNew.type = "text/javascript";
        oNew.textContent = code;
        document.getElementsByTagName("head")[0].appendChild(oNew);
    },
    addCss: function (code) {
        var oNew = document.createElement("style");
        oNew.textContent = code;
        document.getElementsByTagName("head")[0].appendChild(oNew);
    }
    
    };
    
    
    //jsScriptCssLoader.loadFile(["css/1.css","css/2.css","css/3.css"]);
    jsScriptCssLoader.loadFile(["js/common/1.js","js/2.js","js/common/file/fileReader.js"]);
    });
    

提交回复
热议问题