动态加载 / 删除 css 文件以及图片预加载

2,440 阅读1分钟
原文链接: shimo.im
最近,工作中遇到了一个比较奇葩的需求:要在一个页面(PC端)增加一个功能模块,但是这个页面在不久之后要重构,为了新增加的模块可以继续复用,必须做到这个模块的样式对页面其他模块不能造成影响,旧版页面使用bootstrap样式,新版模块只使用normalize.css,UI组件使用sass重写,因为重构工作量太大,公司前端只有1+1个人,所以就想将模块样式独立,最后,用动态加载link标签解决。  

上图为一个页面,所有模块通过哈希控制是否显示,新增了一个约标模块。附上自认为很low的解决方放:(欢迎指正不足)


// 添加link标签
this.loadCss = function(url, callback) {
    var link = document.createElement('link');
    link.type="text/css";
    link.rel = "stylesheet";
    link.href = url+'1';
    document.getElementsByTagName('head')[0].appendChild(link);
    if (callback) {
        callback.call(link);
    }
}
// 通过判断是否为新增模块
if("#" + relId == "#setup_12"){
    self.loadCss('/css/v2.0/pc/new_main.css?v=201702231412', function(){
        self.$_link = this; 
    })
    self.loadCssComplete('/css/v2.0/pc/new_main.css?v=201702231412', function(){
        $("#" + relId).show();  //判断css是够加载完成,如果完成则显示模块
    })
}else{
    if($.isEmptyObject(self.$_link)){
        console.log($.isEmptyObject(self.$_link))
    }else{
        document.getElementsByTagName('head')[0].removeChild(self.$_link);
        self.$_link = new Object();
        window.location.reload();  // 在切换tabs时删除link标签并刷新避免缓冲造成影响
    }
    $("#" + relId).show();
}
将link标签添加到最后,避免bootstrap样式发生覆盖。 特此分享,希望对一些和我一样low的FED有帮助。
附上最近工作中用到的图片资源预加载并显示加载进度条代码:
//构造器函数
function resLoader(config){
    this.option = {
        resourceType : 'image', //资源类型,默认为图片
        baseUrl : './', //基准url
        resources : [], //资源路径数组
        onStart : null, //加载开始回调函数,传入参数total
        onProgress : null, //正在加载回调函数,传入参数currentIndex, total
        onComplete : null //加载完毕回调函数,传入参数total
    }
    if(config){
        for(i in config){
            this.option[i] = config[i];
        }
    }
    else{
        alert('参数错误!');
        return;
    }
    this.status = 0; //加载器的状态,0:未启动   1:正在加载   2:加载完毕
    this.total = this.option.resources.length || 0; //资源总数
    this.currentIndex = 0; //当前正在加载的资源索引
};

resLoader.prototype.start = function(){
    this.status = 1;
    var _this = this;
    var baseUrl = this.option.baseUrl;
    for(var i=0,l=this.option.resources.length; i< l; i++){
        var r = this.option.resources[i], url = '';
        if(r.indexOf('http://')===0 || r.indexOf('https://')===0){
            url = r;
        }
        else{
            url = baseUrl + r;
        }

        var image = new Image();
        image.onload = function(){_this.loaded();};
        image.onerror = function(){_this.loaded();};
        image.src = url;
    }
    if(isFunc(this.option.onStart)){
        this.option.onStart(this.total);
    }
};
resLoader.prototype.loaded = function(){
    if(isFunc(this.option.onProgress)){
        this.option.onProgress(++this.currentIndex, this.total);
    }
    //加载完毕
    if(this.currentIndex===this.total){
        if(isFunc(this.option.onComplete)){
            this.option.onComplete(this.total);
        }
    }
};
var loader = new resLoader({
    resources : [
        'https://xxxyun.com/ydimg/theme/thanksgiving/logo.png',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/ydlogo.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/logo01.png',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/loading_icon.png',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/go.png',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/page_detail01.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/page_detail02.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/page1_bg.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/recivepage_bg01s.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/recivepage_bg02.jpg',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/share.png',
        'https://xxxyun.com/ydimg/theme/2017/01/cutprice/share_path.png'
    ],
    onStart : function(total){
        self.$loadingId.innerText='0%';
        self.$loadingIcon.style.left = '0%';
        self.$loadingCon.style.width = '0%';
    },
    onProgress : function(current, total){
        var percent =Math.floor(current/total*100);
        self.$loadingId.innerText=percent + '%';
        self.$loadingIcon.style.left = percent + '%';
        self.$loadingCon.style.width = percent + '%';
    },
    onComplete : function(total){
        self.$loadingId.innerText='100%';
        self.$loadingIcon.style.left = '100%';
        self.$loadingCon.style.width = '100%';
        document.getElementById('page_loading').style.display = 'none';
    }
});
loader.start();
一枚不会写文章的程序员~