JS_图片预加载——动态方法

JS_图片预加载——动态方法

  • 为什么要使用图片预加载呢?

图片过多时,会提高加载时间,降低网站性能,影响用户体验

  • 图片预加载有什么作用呢?
  1. 预知用户将要发生的行为,提前加载用户所需图片;
  2. 更好的用户体验;
  • 应用场景
  1. 网站的Loading页
  2. 局部图片的加载--表情插件
  3. 漫画网站
  • 外部的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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容