vue3+typescript Implementation of Picture Lazy Loading Plug in

  • 2021-09-04 23:21:25
  • OfStack

github Project Address: github. com/murongg/vue …

Find star and issues

My literary talent is not good, and my articles may not be so good. If you have any questions, you can comment in the message area, and I will try my best to answer them

This project has been published to npm

Installation:


$ npm i vue3-lazyload
# or
$ yarn add vue3-lazyload

Requirement analysis

Support custom loading pictures, which can be used when loading pictures Support custom error pictures, which can be used after the picture fails to load Support lifecycle hooks, similar to the lifecycle of vue, and at the same time img Label binding lazy Property, similar to the

<img src="..." lazy="loading">
<img src="..." lazy="loaded">
<img src="..." lazy="error">

And supports:


 img[lazy=loading] {
  /*your style here*/
 }
 img[lazy=error] {
  /*your style here*/
 }
 img[lazy=loaded] {
  /*your style here*/
 }

Support the use of v-lazy User-defined instruction, which specifies that string/object can be passed in. When string is used, it defaults to url to be loaded. When object is used, it can be passed in

src Image currently to be loaded url loading Pictures used when loading state error Pictures used when loading fails lifecycle This life cycle of lazy replaces the global life cycle

Directory structure


- src
---- index.ts  Entry file, mainly used to register plug-ins 
---- lazy.ts  Main functions of lazy loading 
---- types.ts  Type files, including  interface/type/enum  Wait 
---- util.ts  Shared tool files 

Writing Lazy Load Classes

Lazy loading is mainly realized through IntersectionObserver objects, which may not be supported by some browsers and are not compatible yet.

Determine the parameters passed in when registering plug-ins


export interface LazyOptions {
 error?: string; //  Picture on Load Failure 
 loading?: string; //  Pictures in Load 
 observerOptions?: IntersectionObserverInit; // IntersectionObserver  Object passed in the first 2 Parameters 
 log?: boolean; //  Do you need to print the log 
 lifecycle?: Lifecycle; //  Life cycle  hooks
}

export interface ValueFormatterObject {
 src: string,
 error?: string,
 loading?: string,
 lifecycle?: Lifecycle;
}

export enum LifecycleEnum {
 LOADING = 'loading',
 LOADED = 'loaded',
 ERROR = 'error'
}

export type Lifecycle = {
 [x in LifecycleEnum]?: () => void;
};

Determine the framework of the class

Custom Directives for vue3, supports the following Hook Functions: beforeMount , mounted , beforeUpdate , lazy0 , beforeUnmount , unmounted The specific explanation can be viewed in vue3 document, which only needs to be used at present mounted , lazy0 , unmounted , these three Hook.

Lazy Class basic framework code, lazy.ts :


export default class Lazy {
 public options: LazyOptions = {
  loading: DEFAULT_LOADING,
  error: DEFAULT_ERROR,
  observerOptions: DEFAULT_OBSERVER_OPTIONS,
  log: true,
  lifecycle: {}
 };
 constructor(options?: LazyOptions) {
  this.config(options)   
 }
 
 /**
  * merge config
  * assgin  Method in the  util.ts  File, this article does not repeat this method code, but can be used later  github  View this code in the warehouse 
  *  The main function of this method is to merge two objects 
  *
  * @param {*} [options={}]
  * @memberof Lazy
  */
 public config(options = {}): void {
  assign(this.options, options)
 }
 
	public mount(el: HTMLElement, binding: DirectiveBinding<string | ValueFormatterObject>): void {} //  Correspondence  directive mount hook
 public update() {} //  Correspondence  directive update hook
 public unmount() {} //  Correspondence  directive unmount hook
}

Write lazy loading function


 /**
  * mount
  *
  * @param {HTMLElement} el
  * @param {DirectiveBinding<string>} binding
  * @memberof Lazy
  */
 public mount(el: HTMLElement, binding: DirectiveBinding<string | ValueFormatterObject>): void {
  this._image = el
  const { src, loading, error, lifecycle } = this._valueFormatter(binding.value)
  this._lifecycle(LifecycleEnum.LOADING, lifecycle)
  this._image.setAttribute('src', loading || DEFAULT_LOADING)
  if (!hasIntersectionObserver) {
   this.loadImages(el, src, error, lifecycle)
   this._log(() => {
    throw new Error('Not support IntersectionObserver!')
   })
  }
  this._initIntersectionObserver(el, src, error, lifecycle)
 }
 
 /**
  * force loading
  *
  * @param {HTMLElement} el
  * @param {string} src
  * @memberof Lazy
  */
 public loadImages(el: HTMLElement, src: string, error?: string, lifecycle?: Lifecycle): void {
  this._setImageSrc(el, src, error, lifecycle)
 }

 /**
  * set img tag src
  *
  * @private
  * @param {HTMLElement} el
  * @param {string} src
  * @memberof Lazy
  */
 private _setImageSrc(el: HTMLElement, src: string, error?: string, lifecycle?: Lifecycle): void {    
  const srcset = el.getAttribute('srcset')
  if ('img' === el.tagName.toLowerCase()) {
   if (src) el.setAttribute('src', src)
   if (srcset) el.setAttribute('srcset', srcset)
   this._listenImageStatus(el as HTMLImageElement, () => {
    this._log(() => {
     console.log('Image loaded successfully!')
    })
    this._lifecycle(LifecycleEnum.LOADED, lifecycle)
   }, () => {
    // Fix onload trigger twice, clear onload event
    // Reload on update
    el.onload = null
    this._lifecycle(LifecycleEnum.ERROR, lifecycle)
    this._observer.disconnect()
    if (error) el.setAttribute('src', error)
    this._log(() => { throw new Error('Image failed to load!') })
   })
  } else {
   el.style.backgroundImage = 'url(\'' + src + '\')'
  }
 }

 /**
  * init IntersectionObserver
  *
  * @private
  * @param {HTMLElement} el
  * @param {string} src
  * @memberof Lazy
  */
 private _initIntersectionObserver(el: HTMLElement, src: string, error?: string, lifecycle?: Lifecycle): void {  
  const observerOptions = this.options.observerOptions
  this._observer = new IntersectionObserver((entries) => {   
   Array.prototype.forEach.call(entries, (entry) => {
    if (entry.isIntersecting) {
     this._observer.unobserve(entry.target)
     this._setImageSrc(el, src, error, lifecycle)
    }
   })
  }, observerOptions)
  this._observer.observe(this._image)
 }

 /**
  * only listen to image status
  *
  * @private
  * @param {string} src
  * @param {(string | null)} cors
  * @param {() => void} success
  * @param {() => void} error
  * @memberof Lazy
  */
 private _listenImageStatus(image: HTMLImageElement, success: ((this: GlobalEventHandlers, ev: Event) => any) | null, error: OnErrorEventHandler) {
  image.onload = success 
  image.onerror = error
 }

 /**
  * to do it differently for object and string
  *
  * @public
  * @param {(ValueFormatterObject | string)} value
  * @returns {*}
  * @memberof Lazy
  */
 public _valueFormatter(value: ValueFormatterObject | string): ValueFormatterObject {
  let src = value as string
  let loading = this.options.loading
  let error = this.options.error
  let lifecycle = this.options.lifecycle
  if (isObject(value)) {
   src = (value as ValueFormatterObject).src
   loading = (value as ValueFormatterObject).loading || this.options.loading
   error = (value as ValueFormatterObject).error || this.options.error
   lifecycle = ((value as ValueFormatterObject).lifecycle || this.options.lifecycle)
  }
  return {
   src,
   loading,
   error,
   lifecycle
  }
 }

 /**
  * log
  *
  * @param {() => void} callback
  * @memberof Lazy
  */
 public _log(callback: () => void): void {
  if (!this.options.log) {
   callback()
  }
 }

 /**
  * lifecycle easy
  *
  * @private
  * @param {LifecycleEnum} life
  * @param {Lifecycle} [lifecycle]
  * @memberof Lazy
  */
 private _lifecycle(life: LifecycleEnum, lifecycle?: Lifecycle): void {      
  switch (life) {
  case LifecycleEnum.LOADING:
   this._image.setAttribute('lazy', LifecycleEnum.LOADING)
   if (lifecycle?.loading) {
    lifecycle.loading()
   }
   break
  case LifecycleEnum.LOADED:
   this._image.setAttribute('lazy', LifecycleEnum.LOADED)
   if (lifecycle?.loaded) {
    lifecycle.loaded()
   }
   break
  case LifecycleEnum.ERROR:
   this._image.setAttribute('lazy', LifecycleEnum.ERROR)   
   if (lifecycle?.error) {
    lifecycle.error()
   }
   break
  default:
   break
  }
 }

Writing update hook


 /**
  * update
  *
  * @param {HTMLElement} el
  * @memberof Lazy
  */
 public update(el: HTMLElement, binding: DirectiveBinding<string | ValueFormatterObject>): void {  
  this._observer.unobserve(el)
  const { src, error, lifecycle } = this._valueFormatter(binding.value)
  this._initIntersectionObserver(el, src, error, lifecycle)
 }

Writing unmount hook


 /**
  * unmount
  *
  * @param {HTMLElement} el
  * @memberof Lazy
  */
 public unmount(el: HTMLElement): void {
  this._observer.unobserve(el)
 }

install method needed to write and register plug-ins in index. ts


import Lazy from './lazy'
import { App } from 'vue'
import { LazyOptions } from './types'

export default {
 /**
  * install plugin
  *
  * @param {App} Vue
  * @param {LazyOptions} options
  */
 install (Vue: App, options: LazyOptions): void {
  const lazy = new Lazy(options)

  Vue.config.globalProperties.$Lazyload = lazy
  //  Keep it for standby, for compatibility $Lazyload
  //  Options api , which can be passed through this.$Lazyload Get to Lazy Class, combining an instance of the api I don't know how to get it yet 
  //  So through  provide  To fulfill this requirement 
  //  Usage  const useLazylaod = inject('Lazyload')
  Vue.provide('Lazyload', lazy)
  Vue.directive('lazy', {
   mounted: lazy.mount.bind(lazy),
   updated: lazy.update.bind(lazy),
   unmounted: lazy.unmount.bind(lazy)
  })
 }
}

Using plug-ins


<img src="..." lazy="loading">
<img src="..." lazy="loaded">
<img src="..." lazy="error">
0

App.vue:


<img src="..." lazy="loading">
<img src="..." lazy="loaded">
<img src="..." lazy="error">
1

The above is vue3+typescript picture lazy loading plug-in details, more information about vue3 picture lazy loading please pay attention to other related articles on this site!


Related articles: