Javascript add js libraries by code

后端 未结 3 1331
暖寄归人
暖寄归人 2020-12-22 08:20

I\'m trying to split my long JavaScript code into different libraries.

I\'m trying to write a wrapper script that will load all my libraries:

//this          


        
3条回答
  •  囚心锁ツ
    2020-12-22 08:52

    You would need to use the onreadystatechange handler to ensure that they are loaded in the order required.

    //this file loads all the scripts to the page
    
    $(document).ready(function () {
        var fileName = getCurrentFileName();
        loadScript("scripts/pico/popups.js");
        loadScript("scripts/pico/effects.js");
        loadScript("scripts/pico/pico.js",function(){
            loadScript("scripts/pico/facebook.js");
            if (fileName != null) loadScript("script/pico/" + fileName + ".js");
        });
    });
    
    /**
     * Load a script to the body element
     * @param name the name of script file.js
     */
    function loadScript(name,callback) {
        // Adding the script tag to the body
        var body = document.getElementsByTagName('body')[0];
        var script = document.createElement('script');
        script.onreadystatechange = function(){
            if (script.readyState === "complete" && $.isFunction(callback)) {
                callback();
            }
        }
        script.type = 'text/javascript';
        script.src = name;
        // Fire the loading
        body.appendChild(script);
    }
    

    Since jQuery is already included, it's even easier.

    //this file loads all the scripts to the page
    
    var fileName = getCurrentFileName();
    $.getScript("scripts/pico/popups.js");
    $.getScript("scripts/pico/effects.js");
    $.getScript("scripts/pico/pico.js",function(){
        $.getScript("scripts/pico/facebook.js");
        if (fileName != null) $.getScript("script/pico/" + fileName + ".js");
    });
    

提交回复
热议问题