/*
* @Description: 预加载
* @Author: wangrui
* @Date: 2021-03-02 13:35:34
*/
class PreLoad{
constructor(){
this.images=[]
this.opts={
success:null,
fail:null
}
}
preLoadFn(images,opts){
this.images=typeof(images)==='string'?[images]:images;
this.opts={...this.opts,...opts};
let count=0;
for(var i=0;i<this.images.length;i++){
if(typeof(this.images[i])!=='string')return;
const imageFn=new Image();
imageFn.setAttribute('crossOrigin', 'anonymous');
imageFn.onload=()=>{
this.commonFn(count);
count++;
}
imageFn.onerror=()=>{
this.commonFn(count);
count++;
}
imageFn.src=this.images[i];
}
}
commonFn(count){
this.opts.fail&&this.opts.fail()
if(this.images.length-1===count){
this.opts.success&&this.opts.success()
}
}
}
export default new PreLoad();
前端实现预加载
最新推荐文章于 2025-10-24 10:54:33 发布
这是一个关于JavaScript实现图片预加载的代码示例。预加载函数通过遍历图片数组并设置onload和onerror事件来加载图片,当所有图片加载完成或加载失败时,调用预设的回调函数。预加载对于优化网页性能,尤其是图片密集型页面,有着重要作用。
864

被折叠的 条评论
为什么被折叠?



