Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize lazy loading of vue-lazyload pictures

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to achieve lazy loading of vue-lazyload pictures". In daily operation, I believe that many people have doubts about how to achieve lazy loading of vue-lazyload pictures. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "how to achieve lazy loading of vue-lazyload pictures". Next, please follow the editor to study!

What problem did vue-lazyload solve? (commonly used in projects)

You can imagine that when a web page opens with hundreds of pictures to load, the page will become very stuttered. At this time, if only the images in the visual area are loaded, other images can temporarily have a placeholder loading map. When you scroll them to the visual area, you can request the real picture and replace it. Well, the vue-lazyload plug-in solves this kind of problem.

Lazy loading of vue-lazyload pictures-practice 1. Install plug-ins

Vue-lazyload official website npm configuration address (important)

Https://www.npmjs.com/package/vue-lazyload

Npm I vue-lazyload-- save II. Configuration plugin

Introduce the plug-in for vue-lazyload in the main.js file. (global)

1. Image references in the outermost static directory

Import VueLazyLoad from 'vue-lazyload' / / the picture under the outermost static directory refers to Vue.use (VueLazyLoad, {error:'/ static/images/defaultAvatar.png', / / here is the picture displayed when the image failed to load loading:'/ static/images/defaultAvatar.png', / / here is the picture displayed in the image load attempt: 1, / / load a screen of image preLoad: 1, / / number of failed attempts})

2. Pictures under the assets directory under src

Import VueLazyLoad from 'vue-lazyload' / / Vue.use (VueLazyLoad, {error: require ('common/assets/defaultAvatar.png')) under the assets directory under src, / / here is the picture loading: require (' common/assets/defaultAvatar.png') displayed when the image failed to load, / / here is the picture displayed in the image load attempt: 1, / / load a screen image preLoad: 1, / / number of failed attempts})

* problems encountered in the use of the project, description:

Import VueLazyLoad from 'vue-lazyload'

Error report: Absolute imports should come before relative imports.

Reason: it is mainly about the location of the introduced files.

Third, use plug-ins

Just replace the original: scr= "url" with "url" in the dynamic request img path. Next, take a look at the effect example.

Lazy loading of vue-lazyload pictures-source code 1. Principle analysis

Flow chart of the main processes of lazyload

Brief description of the principle:

1) vue-lazyload is implemented by instruction, and the defined instruction is v-lazy instruction

2) when the instruction is bind, a listener is created and added to the listener queue, and the target dom node is searched to register the dom event (such as the scroll event) for it

3) in the dom event callback above, the listener in listener queue is traversed to determine whether the dom bound by this listener is in the position of perload on the page, and if so, the resource that loads the current image asynchronously

4) at the same time, listener will trigger the current dom rendering function in the three states of loading,loaded,error of the current image loading process, and render the content of dom in the three states respectively.

Second, source code analysis:

1. When the component install is installed, calling LazyClass returns a class object, and then creates an instance of class.

2. Its core is the lazyLoadHandler () function, which is the entry function of picture loading processed by throttling function.

This.lazyLoadHandler = throttle (() = > {let catIn = false this.ListenerQueue.forEach (listener = > {if (listener.state.loaded) return catIn = listener.checkInView () catIn & & listener.load ()}), 200) checkInView () {this.getRect () / / call getBoundingClientRect () return of dom (this.rect.top)

< window.innerHeight * this.options.preLoad && this.rect.bottom >

This.options.preLoadTop) & & (this.rect.left

< window.innerWidth * this.options.preLoad && this.rect.right >

0) / / determine whether the top of dom reaches the position of preload, and whether the bottom of dom reaches the position of preload. The X axis is the same. }

3. Main actions: find the corresponding target (the dom node used to register the dom event; for example, the dom node of the page scrolling), register the dom event for it; create a Listenr for the current dom and add it to the listener queue. Finally, use the lazyLoadHandler () function to load the picture.

4. When the condition is met, call the load () function to load the picture asynchronously.

Load () {/ / if the current attempt to load the picture is greater than the specified number of times, and the current state is still wrong Stop loading action if ((this.attempt > this.options.attempt-1) & & this.state.error) {if (! this.options.silent) console.log ('error end') return} if (this.state.loaded | | imageCache [this.src]) {/ / if return this.render (' loaded') has been cached True) / / use the cache to render the picture} this.render ('loading', false) / / call the elRender () function in lazy. The user switches the src of img to display data and triggers the callback function this.attempt++ / / the corresponding state callback function this.attempt++ / / accumulate this.record (' loadStart') / / record the time of the current state / / load the picture asynchronously Use the Image object to implement loadImageAsync ({src: this.src}, data = > {this.naturalHeight = data.naturalHeight this.naturalWidth = data.naturalWidth this.state.loaded = true this.state.error = false this.record ('loadEnd') this.render (' loaded') False) / / render the content of dom in loaded state imageCache [this.src] = 1 / / the current image is cached in the browser}, err = > {this.state.error = true this.state.loaded = false this.render ('error', false)})}

5. LoadImageAsync asynchronously loads pictures and realizes network requests through image objects.

Const loadImageAsync = (item, resolve, reject) = > {let image = new Image () image.src = item.src image.onload = function () {resolve ({naturalHeight: image.naturalHeight, / / actual height of the picture naturalWidth: image.naturalWidth, src: image.src})} image.onerror = function (e) {reject (e)}}

6. The update () function of lazy class, that is, the callback function that starts when the data bound by the v-lazy instruction changes.

Update (el, binding) {/ / gets the data of the image src bound by the current dom. If the current dom has performed the load process, reset the image data and status of the current dom let {src, loading, error} = this.valueFormatter (binding.value) / / the currently bound value is obj, and select {src, loading, error} Is string, then it is used as src / / to find the current dom bound listener const exist = find (this.ListenerQueue, item = > item.el = el) / / to update the status and status of listener corresponding to the picture resource exist & & exist.update ({src, loading, error}) this.lazyLoadHandler () Vue.nextTick (() = > this.lazyLoadHandler ())} so far The study on "how to achieve lazy loading of vue-lazyload pictures" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report