沒事擼個插件玩1--預加載插件(f-preload)

沒事擼個插件玩--預加載插件(f-preload)

原生無依賴,預加載插件

插件名:f-preload
實現的主要功能:
一、批量預加載多個圖片
二、支持debug打印加載信息
三、支持加載完執行自定義回調函數

項目github地址https://github.com/ifir/f-preload各位客官賞個star,表示很開心git

如何使用

一、頁面引入github

<script src="youpath/f-preload.js"></script>

var Fpreload = new Fpreload({
    source: Array,  //圖片src數組(required)
    debug : Boolean,  //默認false
    callback : Function //默認null
});

or:

二、npm安裝npm

npm install --save f-preload數組

var Fpreload = require('f-preload');
var preload = new Fpreload({
    source: Array,  //圖片src數組(required)
    debug : Boolean,  //默認false
    callback : Function //默認null
});

原理解釋:

一句話解釋:利用img.src發起http請求
看看核心代碼異步

imgloader:function(){
    var _this = this,
        img = [],
        source = _this.source,
        sucNum = _this.sucNum;
    _this.asyncNum = 0;//計數器
    for(var i = 0; i < _this.length; i++){
        //實例
        img[i] = new Image();
        //加載
        img[i].src = source[i];
        //加載完成
        img[i].onload = function(){
            _this.sucNum++;
            _this.asyncNum++;
            if(_this.sucNum == _this.length){
                if(typeof _this.callback === 'function'){
                    _this.callback();
                }else{
                    console.log('Preloader Complete');
                }
            }
            //log打印
            _this.debug && _this.msglog();
        };
        //加載失敗
        img[i].onerror = function(){
            _this.errNum++;
            _this.asyncNum++;
            _this.errArr.push(this.src);
            //log打印
            _this.debug && _this.msglog();
        }
    }
}

這裏說明一下onload指圖片加載完成,onerror不解釋,還要說明一下onload是異步的,爲了debug模式在全部的圖片onload和onerror以後在打印加載圖片的信息。還有自定義回調函數只有在全部圖片都加載成功纔會執行,而不是一張圖片加載成功就執行。async

debug模式用開發時記錄圖片的加載信息

console.log很熟悉吧,下面的不知道的趕忙度娘一下吧
console.group
console.time
console.info
console.warn
console.error

預告

下篇文章就寫這個插件f-lazyload,我已經寫了差很少了,是個懶加載插件
具體細節先去github看一吧[f-lazyload倉庫](https://github.com/ifir/f-lazyload)
重要的事情說三遍star,star,star你的支持就是動力
相關文章
相關標籤/搜索