dynamic script loader in JS

做~自己de王妃 提交于 2020-01-14 05:50:25

问题


How can i write dynamic MULTIPLE script loader with complete handler like google

google.load("http://script1");
google.load("http://script2");
google.setOnLoadCallback(function(){});

thanks


回答1:


My advise is not to bother with script loading yourself, unless you take a look at how some frameworks do it because there can be security risks for your application with that sort of thing. In fact, I would redirect you to JQuery instead as it does have that functionality implemented (see here).




回答2:


There are open source js which will ease your problem. You can use LABJS or RequreJS plugins.

Script loaders like LABJS, RequireJS will improve the speed and quality of your code. Additionally it will load scripts dynamically.




回答3:


I wrote like that

myApp.Loader = function(){
    var queries = [];
    var q = 0;
    var p = 0;
    var started = false;
    var _callback = function(){};

    var start = function(){
        if(queries.length > 0 && !started){
            started = true;
            load(queries.shift());
        } else if(queries.length > 0 && started){
            load(queries.shift());
        } else if(queries.length == 0 && started){
            started = false;
            if(q > 0 && q == p){
                callback();
            }
        }
    };

    var load = function(fullUrl){
        $.getScript(fullUrl, function() {
            p++;
            start();
        });
    };

    var callback = function(){
        _callback();
    };

    this.setCallback = function(fnc){
        _callback = fnc;
        if(q > 0 && q == p){
            callback();
        }
    };

    this.addQuery = function(query){
        queries.push(query);
        q++;
        if(!started) {
            start();
        }
    };

    return this;
}

var Loader = new myApp.Loader();

myApp.load = function(fullUrl){
    Loader.addQuery(fullUrl);
}

myApp.setOnLoadCallback = function(fnc){
    Loader.setCallback(fnc);
}

and call it

myApp.load("http://script1");
myApp.load("http://script2");
myApp.load("http://script3");
myApp.setOnLoadCallback(function(){
    // complete script load handling
});


来源:https://stackoverflow.com/questions/3475702/dynamic-script-loader-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!