1. First, let me explain what lazy image loading is:
When we use the software, there will be many images that need to be loaded, but when the network environment is poor or the memory is insufficient, the user's first screen will be loaded very slowly, affecting the user experience. Therefore, in order to solve this problem, a lazy image loading method was proposed to solve the problem.
2. Solution:
①Pictures are loaded only when the image area reaches the user interface visual area
② When the first screen is loaded, the img tag src is assigned to an empty value, so that it will not waste time rendering invisible pictures
③ When the user slides to the visual area of the picture, replace the path of src and change it to the official path, and start rendering the picture.
3. Benefits:
The advantage of this is that you can use the current network environment to fully load the pictures in the visual area to increase the loading speed; it will not be loaded when the pictures do not reach the visual area, avoiding wasting performance
4. Code implementation (vue2):
① Document
<template> <div class="app"> <div class="top">fjdskla</div> <div><img v-lazy src="../static/image/" alt="img" /></div> <div><img v-lazy src="../static/image/" alt="img" /></div> <div><img v-lazy src="../static/image/" alt="img" /></div> <div><img v-lazy src="../static/image/" alt="img" /></div> </div> </template> <script> export default { data() { return {} }, created() {}, mounted() {}, methods: {}, } </script> <style scoped lang="scss"> .app { .top { height: 2000px; width: 100%; background-color: beige; } div { margin-top: 50px; } } </style>
② Set global custom command Named lazy
// Define lazy loading pictures or files, etc., custom commands('lazy', (el, binding) => { let oldSrc = //Save old src to facilitate the assignment of real src paths during post-rendering = "" // Assign the rendered src to empty, the picture will not be rendered let observer = new IntersectionObserver(([{ isIntersecting }]) => { // Call the method to find whether the elDOM element is in the visible area if (isIntersecting) { //Whether the callback is in the visible area, true or false = oldSrc //If it is in the visible area, give the DOM element rendering the original saved real path to the original DOM element. (el) // Just listen once, and you will not listen when you slide to the visual area the second time } }) (el) // Call method})
5. Disadvantages
The IntersectionObserver method may not be compatible with the full browser. If you want to implement the full browser compatible, you can introduce the corresponding plug-in implementation.
Summarize
This is the end of this article about the implementation of lazy loading code for vue images. For more related lazy loading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!