CSS、JS动态加载,加强版

var dcLoader = {
    load: function(option,callback){
        var _type = "",_url = "";
        var _callback = callback
        option.type? _type = option.type:"";
        option.url? _url = option.url:"";
        typeof option.filtration === "boolean"? filtration = option.filtration:"";
        switch(_type){
            case "js":
            case "javascript": this.js(_url,_callback); break;
            case "css": this.link(_url,_callback); break;
        }
        return this;
    },
    js: function(url,callback){
        var urls = url.replace(/[,]\s*$/ig,"").split(",");
        var scripts = [];
        var completeNum = 0;
        for( var i = 0; i < urls.length; i++ ){
            scripts[i] = document.createElement("script");
            scripts[i].type = "text/javascript";
            scripts[i].src = urls[i];
            document.getElementsByTagName("head")[0].appendChild(scripts[i]);
            if(!this.func(callback)){return this;}
            if(scripts[i].readyState){
                scripts[i].onreadystatechange = function(){
                    if( this.readyState === "loaded" || this.readyState === "complete" ){
                        this.onreadystatechange = null;
                        completeNum++;
                        completeNum >= urls.length ? callback () : '';
                    }
                }
            }else{
                scripts[i].onload = function(){
                    completeNum ++;
                    completeNum >= urls.length ? callback () : '';
                }
            }

        }
        return this;
    },
    link : function(url,callback){
        var urls = url.replace(/[,]\s*$/ig,"").split(",");
        var links = [];
        for( var i = 0; i < urls.length; i++ ){
            links[i] = document.createElement("link");
            links[i].rel = "stylesheet";
            links[i].href = urls[i];
            document.getElementsByTagName("head")[0].appendChild(links[i]);
        }
        this.func(callback) ? callback() : '';
        return this;
    },
    func : function isFunction(fn) {
        return Object.prototype.toString.call(fn)=== '[object Function]';
    }
};

Continue reading...



about me

  • 陶之11's Blog Name:陶之11 OICQ:14779023 Site:Pao11.com

分类

快捷入口