Dynamically load a JavaScript file

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

    Here a simple example for a function to load JS files. Relevant points:

    • you don't need jQuery, so you may use this initially to load also the jQuery.js file
    • it is async with callback
    • it ensures it loads only once, as it keeps an enclosure with the record of loaded urls, thus avoiding usage of network
    • contrary to jQuery $.ajax or $.getScript you can use nonces, solving thus issues with CSP unsafe-inline. Just use the property script.nonce
    var getScriptOnce = function() {
    
        var scriptArray = []; //array of urls (closure)
    
        //function to defer loading of script
        return function (url, callback){
            //the array doesn't have such url
            if (scriptArray.indexOf(url) === -1){
    
                var script=document.createElement('script');
                script.src=url;
                var head=document.getElementsByTagName('head')[0],
                    done=false;
    
                script.onload=script.onreadystatechange = function(){
                    if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
                        done=true;
                        if (typeof callback === 'function') {
                            callback();
                        }
                        script.onload = script.onreadystatechange = null;
                        head.removeChild(script);
    
                        scriptArray.push(url);
                    }
                };
    
                head.appendChild(script);
            }
        };
    }();
    

    Now you use it simply by

    getScriptOnce("url_of_your_JS_file.js");
    

提交回复
热议问题