JS_图片预加载——动态方法
- 为什么要使用图片预加载呢?
图片过多时,会提高加载时间,降低网站性能,影响用户体验
- 图片预加载有什么作用呢?
- 预知用户将要发生的行为,提前加载用户所需图片;
- 更好的用户体验;
- 应用场景
- 网站的Loading页
- 局部图片的加载--表情插件
- 漫画网站
- 外部的JS模块
export default class ReLoad {
num = 0;
imgList = [];
//图片数组,回调函数,图片路径,扩展名
constructor(_imgArr, _callBack, _basePath, _expa) {
if (!_basePath) _basePath = "";
if (!_expa) _expa = "";
if (_basePath.length > 0 && _basePath[_basePath.length - 1] !== "/") _basePath += "/";
if (_expa.length > 0 && _expa[0] !== ".") _expa = "." + _expa;
this.imgArr = _imgArr;
this.callBack = _callBack;
this.basePath = _basePath;
this.expa = _expa;
let img = new Image();
this.loadHandlerBind = e => { this.loadHandler(e) };
img.addEventListener("load", this.loadHandlerBind);
var path = _basePath + _imgArr[this.num] + _expa;
img.src = path;
}
loadHandler(e) {
this.imgList.push(e.currentTarget.cloneNode(false));
this.num++;
if (this.num > this.imgArr.length - 1) {
e.currentTarget.removeEventListener("load", this.loadHandlerBind);
if (this.callBack) {
this.callBack(this.imgList);
return;
} else {
var evt = new Event("finish");
evt.imgList = this.imgList;
document.dispatchEvent(evt);
return;
}
}
e.currentTarget.src = this.basePath + this.imgArr[this.num] + this.expa;
}
}
- 在预加载HTML页面引入
<script type="module">
import Reload from "./js/Reload.js";
let arr=["a","b","c","d","e"];
let load = new Reload(arr,callBack,"./img",".jpg");
function callBack(list){
console.log(list);
}
</script>
-
如果动态方法还不过瘾的话,来看看这篇升级版的静态方法吧