JS_多图片同时异步加载
使用静态方法,完成预加载和存储功能
- LoadVo.js
export default class LoadVo {
imgArr;
callBack;
basePath;
expa;
fn;
num = 0;
imgList = [];
finish = false;
//图片数组,回调函数,图片路径,扩展名
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;
}
start(_fn) {
let img = new Image();
this.loadHandlerBind = e => { this.loadHandler(e) };
img.addEventListener("load", this.loadHandlerBind);
var path = this.basePath + this.imgArr[this.num] + this.expa;
img.src = path;
this.fn = _fn;
}
loadHandler(e) {
this.imgList.push(e.currentTarget.cloneNode(false));
this.num++;
if (this.num > this.imgArr.length - 1) {
e.currentTarget.removeEventListener("load", this.loadHandlerBind);
this.fn(this);
return;
}
e.currentTarget.src = this.basePath + this.imgArr[this.num] + this.expa;
}
}
- 在ReLoad.js中引入上面的LoadVo
import LoadVo from "./LoadVo.js";
export default class Reload {
static dic = {}
static load(id, _imgArr, _callBack, _basePath, _expa) {
let loadVo = new LoadVo(_imgArr, _callBack, _basePath, _expa);
Reload.dic[id] = loadVo;
loadVo.start(Reload.finishHandler);
}
static finishHandler(elem) {
elem.callBack(elem.imgList);
elem.finish = true;
}
static getFinishList(id) {
return Reload.dic[id].imgList;
}
}
- 在预加载HTML页面引入
<script type="module">
import Reload from "./js/ReLoad.js";
let arr=["./img/a.jpg","./img/b.jpg","./img/c.jpg","./img/d.jpg"];
let arr1=["a","b","c","d","e"];
Reload.load("a",arr,callBack);
Reload.load("b",arr1,callBack1,"./img/",".jpeg");
function callBack(list){
console.log(list);
}
function callBack1(list){
console.log(list);
fn();
}
function fn(){
console.log(Reload.getFinishList("b"));
}
</script>
初次使用难以理解,如果感觉有难度,可以先看看这篇动态方法!