插件名: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 });
二、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
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你的支持就是动力