SoFunction
Updated on 2025-04-12

Vue implements a lazy image loading plugin

Preface

Lazy image loading is a very common feature, especially for some e-commerce platforms, which is crucial for performance optimization. Today I will use vue to implement a plug-in for lazy image loading. This blog adopts the "three-step" strategy - (), Vue image lazy loading plug-in, and gradually implements a Vue image lazy loading plug-in.

()

Just like when developing a jQuery plug-in, we need to use () to develop a Vue plug-in. In fact, it is a method that is implemented internally by the official, allowing developers to flexibly develop their own plug-ins. Just develop according to the agreed rules.

usage

Install the plugin. If the plugin is an object, the install method must be provided. If the plugin is a function, it will be used as the install method. When the install method is called, Vue will be passed in as a parameter.

This method needs to be called before calling new Vue().

When the install method is called multiple times by the same plugin, the plugin will only be installed once.

Note:The first parameter of the install method or method that is regarded as the install method is the Vue constructor, and the second parameter is an optional option object.

Reference link:

  • /v2/api/#Vue-use
  • https:///article/ 

Custom commands

Usage—Global and local registration

Global registration

// Register a global custom command `v-focus`('focus', {
 // When the bound element is inserted into the DOM... inserted: function (el) {
 // Focus elements ()
 }
})

Local registration

directives: {
 focus: {
 // Definition of instructions inserted: function (el) {
 ()
 }
 }
}

Hook function

A directive definition object can provide the following hook functions (all optional):

  • bind: Only called once, the instruction is called the first time it is bound to an element. Here you can perform one-time initialization settings.
  • inserted: Called when the bound element is inserted into the parent node (only the parent node exists, but it may not be inserted into the document).
  • update: Called when the VNode of the component is updated, but may occur before its child VNode is updated. The value of the instruction may have changed or not. However, you can ignore unnecessary template updates by comparing the values ​​before and after the update (see below for detailed hook function parameters).
  • componentUpdated: Called after the VNode and its child VNode of the component where the directive is located.
  • unbind: It is called only once, and is called when the directive is unbined with the element.

Parameters of hook function

  • el: The element bound to the directive can be used to directly operate the DOM.
  • binding: An object containing the following properties:
  • name: directive name, excluding v- prefix.
  • value: The binding value of the directive, for example: v-my-directive="1 + 1", the binding value is 2.
  • oldValue: The previous value bound by the directive, available only in the update and componentUpdated hooks. Available regardless of whether the value changes or not.
  • expression: A directive expression in the form of a string. For example, in v-my-directive="1 + 1", the expression is "1 + 1".
  • arg: The parameter passed to the instruction, optional. For example, in v-my-directive:foo, the parameter is "foo".
  • modifiers: An object containing modifiers. For example: In , the modifier object is { foo: true, bar: true }.
  • vnode: Vue compiles the generated virtual node. Move the VNode API to learn more.
  • oldVnode: Previous virtual node, available only in update and componentUpdated hooks.

Reference link:/v2/guide/

Vue picture lazy loading plug-in implementation

Idea: Provide two empty arrays listenList (collect unloaded image elements and resources) and imageCacheList (collect loaded image resources). Then, determine whether the image has reached the viewing area. If it has arrived, use the Image object to load the resource image. After loading, assign it to the src of the bound element to display it. At the same time, put the loaded resources into the imageCacheList array and use the isAlredyLoad method to make a judgment to prevent the same resources from loading repeatedly later. If it is not reached, put the element and resource objects into the listenList array and finally perform scrolling monitoring. Listen to whether elements in the listenList array can load resources.

Plugin implementation:

// Introduce Vue constructorimport Vue from 'vue'

var lazyload = {
 // () load install by default, and pass Vue as the first parameter install(vue,payload) {
 // Array expansion removes elements if(!){
  = function(item){
 if(!) return
 var index = (item);
 if( index > -1){
 (index,1);
 return this
 }
 }
 }

 // Default value picture var defaultImage =  || '/tps/i1/';
 var errorImage =  || '/tps/i1/';
 // Pictures are loaded when 10px away from the viewing area by default var distanece =  || 10;
 // Collect unloaded image elements and resources var listenList = [];
 // Collect loaded image elements and resources var imageCacheList = [];

 // Whether the completed picture has been loaded const isAlredyLoad = (imageSrc) => {
 if((imageSrc) > -1){
 return true;
 }else{
 return false;
 }
 }

 //Check whether the image can be loaded, and if so, load it const isCanShow = (item) =>{
 var ele = ;
 var src = ;
 //The distance from the top of the page var top = ().top;
 //The height of the page's visible area var windowHeight = ;
 // top - distance There are distance pixels to the visual area if(top - distanece < ){ 
 var image = new Image();
  = src;
  = function() {
  = src;
 (src);
 (item);
 }
  = function() {
  = errorImage;
 (src);
 (item);
 }
 return true;
 }else{
 return false;
 }
 };

 const onListenScroll = () => {
 ('scroll',function(){
 var length = ;
 for(let i = 0;i<length;i++ ){
 isCanShow(listenList[i]);
 }
 })

 }

 //The final method of Vue instruction const addListener = (ele,binding) =>{
 //Binding image address var imageSrc = ;

 // Prevent duplicate loading.  If it has been loaded, you do not need to reload it, and directly assign src if(isAlredyLoad(imageSrc)){ 
  = imageSrc;
 return false;
 }

 var item = {
 ele: ele,
 src: imageSrc
 }

 //The picture shows the default picture  = defaultImage;

 //See again if this picture can be displayed if(isCanShow(item)){
 return
 }

 // Otherwise, put the image address and elements into the listening lisenList (item);
 
 //Then start listening to the page scroll event onListenScroll();
 }

 ('lazyload',{
 inserted: addListener,
 updated: addListener
 })
 }
}

export default lazyload;

Plugin calls:

import Vue from 'vue'
import App from './App'
import router from './router'
import Lazyload from './common/js/lazyload'

// All parameters are optional(Lazyload,{
 scrollDistance: 15, // Development and loading resources when there are 15px left to the visual area defaultImage: '', // Default image before resource image is not loaded (absolute path) errorImage:'' // The resource to be loaded when the resource image fails to load (absolute path)})

Reference link:https:///article/

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.