关于图片加载,你需要学习一下

我的设计想法是:通过一个加载类,传入 dom 元素、 props 和 emit。先创建出一个虚拟的 image 元素进行尝试加载,加载成功获失败都会进入下一步的函数,做出对应从处理逻辑。

初步设计

class Load {
  constructor(node, props, emit) {
    this.node = node
    this.props = props
    this.emit = emit
  }
  // 加载 src
  loadCreateImg = () => {
    const newImg = new Image() // 新建一个虚拟的 img

    newImg.src = this.props.src // 将传入的 src 赋值给虚拟节点

    // src 加载失败
    newImg.addEventListener('error', (evt) => {
      // 加载失败的处理
    })

    // src 加载成功
    newImg.addEventListener('load', (evt) => {
      // 加载成功的处理
    })
  }
}

首先我创建了一个Load的加载类,需要传入node参数作为最终需要渲染的dom节点,props是传入的组件内部的props参数,内部包含图片需要加载的src路径,emit包括一些回调参数。

类的内部有个loadCreateImg的方法,调用可创建一个虚拟的Image元素,直接将传入的props.src赋值并加载。监听上面的errorload事件,即可监听到图片是否加载成功,以便做出不同的状态。

成功和失败

对于成功或失败的处理,我新增了onerroronload方法,来处理加载成功和失败之后的不同处理状态

class Load {
  constructor(node, props, emit) {
    this.node = node
    this.props = props
    this.emit = emit
  }
  loadCreateImg = () => {
    const newImg = new Image()

    newImg.src = this.props.src

    newImg.addEventListener('error', (evt) => {
      this.onerror(evt) // 新增
    })

    newImg.addEventListener('load', (evt) => {
      this.onload(evt) // 新增
    })
  }
  // 加载成功
  onload = (evt) => {
    this.node.src = this.props.src
  }
  // 加载失败
  onerror = (evt) => {
    // ……
  }
}

对于加载成功,处理方式是,将传入的真是的 dom 节点直接赋值给传入的 props.src 即可完成加载。

加载失败

class Load {
  constructor(node, props, emit) {
    this.node = node
    this.props = props
    this.emit = emit
  }
  loadCreateImg = (errSrc?: string) => {
    const newImg = new Image()

    // 如果 errSrc 存在 就尝试加载 errSrc
    if (errSrc) {
      newImg.src = errSrc
    } else {
      newImg.src = this.props.src
    }

    newImg.addEventListener('error', (evt) => {
      this.onerror(evt)
    })

    newImg.addEventListener('load', (evt) => {
      this.onload(evt)
    })
  }
  onload = (evt) => {
    this.node.src = this.props.src
  }
  // 加载失败
  onerror = (evt) => {
    // 如果存在 errSrc 则继续尝试加载
    if (this.props.errSrc) {
      // 将 errSrc 传给 loadCreateImg 方法
      return this.loadCreateImg(this.props.errSrc)
    }

    // 否则返回失败回调
    this.emit('error', evt)
  }
}

但是上面代码存在两个问题:

  • 首先我们发现,在 onload 加载成功的方法中,将真实 dom 始终赋值的始终 是 src
onload = (evt) => {
  // 始终赋值为 props.src
  this.node.src = this.props.src
}

但是src并不是始终可以加载成功的,所以还是需要动态的去将真正加载成功的src传给onload方法,那么真正加载成功的src也就是在load方法中。并且还要加入成功的emit

  • 其次,在处理加载失败的onerror方法中,因为判断了如果存在errSrc就继续调用 loadCreateImg加载方法重新加载。问题是,如果传入了errSrc那么if (this.props.errSrc)其实是始终为真的,这也就导致了死循环,会重复调用加载函数。
onerror = (evt) => {
  // 判断始终为真
  if (this.props.errSrc) {
    return this.loadCreateImg(this.props.errSrc)
  }

  // 否则返回失败回调
  this.emit('error', evt)
}

所以就需要给它一个可以变为假的时机,那么修复方法为:在传给loadCreateImg方法之后,将errSrc清空,这样加载一次之后就可以判断为假了,所以完整代码为:

class Load {
  constructor(node, props, emit) {
    this.node = node
    this.props = props
    this.emit = emit
  }
  loadCreateImg = (errSrc?: string) => {
    const newImg = new Image()

    // 如果 errSrc 存在 就尝试加载 errSrc
    if (errSrc) {
      newImg.src = errSrc
    } else {
      newImg.src = this.props.src
    }

    newImg.addEventListener('error', (evt) => {
      this.onerror(evt)
    })

    newImg.addEventListener('load', (evt) => {
      this.onload(evt, newImg.src) // 将加载成功的 src 传给 onload 函数
    })
  }
  // 新增 src 属性
  onload = (evt, src: string) => {
    this.node.src = src // 将真实 dom 的 src 赋值给传入的 src
    this.emit('load', evt) // 新增
  }
  onerror = (evt) => {
    if (this.props.errSrc) {
      this.loadCreateImg(this.props.errSrc)
      this.props.errSrc = '' // 清空 errSrc 避免重复调用死循环
      return
    }

    this.emit('error', evt)
  }
}

回调函数

class Load {
  constructor(node, props, emit, callback) {
    this.node = node
    this.props = props
    this.emit = emit
    this.callback = callback // 新增 callback 参数
  }
  loadCreateImg = (errSrc?: string) => {
    const newImg = new Image()

    if (errSrc) {
      newImg.src = errSrc
    } else {
      newImg.src = this.props.src
    }

    newImg.addEventListener('error', (evt) => {
      this.onerror(evt)
    })

    newImg.addEventListener('load', (evt) => {
      this.onload(evt, newImg.src)
    })
  }
  onload = (evt, src: string) => {
    this.node.src = src
    this.emit('load', evt)

    // 如果 callback 存在,在加载成功的时候返回 true
    if (this.callback) {
      this.callback(true)
    }
  }
  onerror = (evt) => {
    if (this.props.errSrc) {
      this.loadCreateImg(this.props.errSrc)
      this.props.errSrc = ''
      return
    }

    this.emit('error', evt)
    // 如果 callback 存在,在加载失败的时候返回 false
    if (this.callback) {
      this.callback(false)
    }
  }
}

懒加载

图片的懒加载,也是一个图片加载必备的功能了,这里我使用的是内置的IntersectionObserveropen in new window接口,对于这个方法,这里不过多描述,各位可以通过MDNopen in new window进行学习。

对于懒加载,因为这是一个可选的属性,并不是每次都需要,所以我将懒加载单独抽离出来的一个 Lazy 类进行实现,再将Lazy类继承到Load类,代码如下:

class Lazy extends Load {
  constructor(img, props, emit, callback) {
    // super 关键字调用
    super(img, props, emit, callback)
  }
  observer = () => {
    const observer = new IntersectionObserver(
      (arr): void => {
        // 如果进入可视区域
        if (arr[0].isIntersecting) {
          // 开始加载图片 调用父类
          this.loadCreateImg()
          observer.unobserve(this.node)
        }
      },
      /**
       * rootMargin 为触发懒加载的距离 通过 props 传入
       * https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin
       */
      { rootMargin: this.props.rootMargin }
    )
    return observer
  }
  // 执行 懒加载
  lazyCreateImg = (): void => {
    // IntersectionObserver 内部方法,需要将 dom 节点传入
    this.observer().observe(this.node)
  }
}

IntersectionObserver接口可以判断dom元素是否进入可视区域,通过内置方法判断进入可视区域之后,执行父类的loadCreateImg方法进行加载,从而实现懒加载。

对外接口

// 导出对外接口
export const loadImage = (node, prop, emit, callback) => {
  /**
   * 如果传入了 lazy 则执行懒加载类
   * 否则执行正常加载类
   */
  if (prop.lazy) {
    const lazy = new Lazy(node, prop, emit, callback)
    return lazy.lazyCreateImg()
  }
  const load = new Load(node, prop, emit, callback)
  load.loadCreateImg()
}

测试使用

<script lang="ts" setup>
  import { loadImage } from './load.js'
  import { ref, onMounted } from 'vue'

  const myImg = ref(null as unknown as HTMLImageElement)

  // 模拟 props
  const props = {
    src: 'https://tianyuha2o.cn/images/auto/my.jpg',
    errSrc: 'https://tianyuhao.cn/images/auto/4.jpg',
    lazy: true
  }

  onMounted(() => {
    loadImage(myImg.value, props)
  })
</script>

<template>
  <img ref="myImg" src="" />
</template>

完整代码

点击查看详情
/**
 * 判断一个值是否为字符串
 * @param target 要检测的值
 * @returns boolean
 */
export const isString: i = (target: unknown): target is string => {
  return (
    typeof target === 'string' &&
    Object.prototype.toString.call(target) === '[object String]'
  )
}

/**
 * Load 类所需要的 props 参数
 */
export interface LoadNeedImagePropsInterface {
  src: string
  errSrc: string
  rootMargin: string
  lazy: boolean
}

export interface LazyInterface {
  observer(): IntersectionObserver
  lazyCreateImg(): void
}

export interface LoadImageInterface {
  (
    node: HTMLImageElement,
    prop: LoadNeedImagePropsInterface,
    emit: Function,
    callback: callbackInterface | null
  ): void
}

export interface LoadInterface {
  node: HTMLImageElement
  props: LoadNeedImagePropsInterface
  emit: Function
  callback: callbackInterface | null
  loadCreateImg(errSrc?: string): void
  onerror(evt: Event): void
  onload(evt: Event, src: string): void
}

export interface CallbackInterface {
  (params: boolean): void
}

/**
 * 图片加载
 */
class Load implements LoadInterface {
  node: HTMLImageElement
  props: LoadNeedImagePropsInterface
  emit: Function
  callback: CallbackInterface | null

  /**
   * @param node 图片 dom 节点
   * @param props props 参数
   * @param emit 事件
   * @param callback 回调参数
   */
  constructor (
    node: HTMLImageElement,
    props: LoadNeedImagePropsInterface,
    emit: Function,
    callback: CallbackInterface | null
  ) {
    this.node = node
    this.props = props
    this.emit = emit
    this.callback = callback
  }
  /**
   * 第一步会进入到这里
   * 首先加载当前的 src 地址图片
   * @param errSrc src 失败后的加载路径
   */
  loadCreateImg = (errSrc?: string): void => {
    const newImg: HTMLImageElement = new Image()

    if (errSrc) {
      newImg.src = errSrc
    } else {
      newImg.src = this.props.src
    }

    // src 加载失败
    newImg.addEventListener('error', (evt: Event): void => {
      this.onerror(evt)
    })

    // src 加载成功
    newImg.addEventListener('load', (evt: Event): void => {
      this.onload(evt, newImg.src)
    })
  }
  /**
   * 加载失败
   * @param evt 事件对象
   * @returns
   */
  onerror = (evt: Event): void => {
    // 如果存在 errSrc 则继续尝试加载
    if (this.props.errSrc) {
      this.loadCreateImg(this.props.errSrc)
      this.props.errSrc = ''
      return
    }

    // 否则返回失败回调
    this.emit('error', evt)
    if (this.callback) {
      this.callback(false)
    }
  }
  /**
   * 图片加载
   * @param evt 事件对象
   * @param src 需要加载的 src
   */
  onload = (evt: Event, src: string): void => {
    this.node.src = src
    this.emit('load', evt)

    if (this.callback) {
      this.callback(true)
    }
  }
}

/**
 * 图片懒加载
 * 使用 IntersectionObserver 监视图片
 * https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver/observe
 */
class Lazy extends Load implements LazyInterface {
  constructor (
    img: HTMLImageElement,
    props: LoadNeedImagePropsInterface,
    emit: Function,
    callback: CallbackInterface | null
  ) {
    super(img, props, emit, callback)
  }
  /**
   * 懒加载函数
   * @returns
   */
  observer = (): IntersectionObserver => {
    const observer: IntersectionObserver = new IntersectionObserver(
      (arr: IntersectionObserverEntry[]): void => {
        if (arr[0].isIntersecting) {
          this.loadCreateImg()
          observer.unobserve(this.node)
        }
      },
      {
        rootMargin: isString(this.props.rootMargin)
          ? this.props.rootMargin
          : this.props.rootMargin + 'px'
      }
    )
    return observer
  }
  /**
   * 执行懒加载
   */
  lazyCreateImg = (): void => {
    this.observer().observe(this.node)
  }
}

/**
 * 判断是懒加载还是正常加载
 * @param node img 元素
 * @param prop Props
 * @param emit Emits
 * @param callback 回调函数
 */
export const loadImage: LoadImageInterface = (
  node: HTMLImageElement,
  prop: LoadNeedImagePropsInterface,
  emit: Function,
  callback: CallbackInterface | null
): void => {
  /**
   * 如果传入了 lazy 则执行懒加载类
   * 否则执行正常加载类
   */
  if (prop.lazy) {
    const lazy: Lazy = new Lazy(node, prop, emit, callback)
    return lazy.lazyCreateImg()
  }
  const load: Load = new Load(node, prop, emit, callback)
  return load.loadCreateImg()
}
贡献者: mankueng