Dynamically load a JavaScript file

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

    Here is a simple one with callback and IE support:

    function loadScript(url, callback) {
    
        var script = document.createElement("script")
        script.type = "text/javascript";
    
        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }
    
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    
    loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
    
         //jQuery loaded
         console.log('jquery loaded');
    
    });
    

提交回复
热议问题