Vue project – Image lazy loading
Image lazy loading principle: when the image enters the viewable area, then the image address is assigned to the IMG SRC attribute requirements: when the image enters the viewable area to load the image, and handle the loading failure
Listen for pictures entering the viewable area
- native
WebAPI
:IntersectionObserver
- The basic use
// Create the observed object instance
const observer = new IntersectionObserver(callback[, options])
const obs = new IntersectionObserver((entries, observer) = > {
// entries = [{isIntersecting: true}]
}, {})
obs.observe(imgDom)
obs.unobserve(imgDom)
// Callback is triggered when the DOM enters and leaves the viewable area
// - Two callback parameters entries, observer
// - entries Array of observed element information objects [{element information},{}], where isIntersecting determines whether to enter or leave
// - observer is an example of an observation
// options Configures parameters
// - Three configuration attributes root rootMargin threshold
// - root Indicates the scrolling container. The default is document
// -rootMargin Indicates whether the container has a margin
// - threshold Indicates the crossover ratio
The instance provides two methods
// Observe (dom) Observe which DOM
// unobserve(dom) stop looking at that DOM
Copy the code
Function implementation
- To facilitate the use of all images in your project, encapsulate them as custom instructions (Vue3.0)
// src/components/index.js
import defaultImg from '@/assets/images/001.jpg'
export default {
install(app) {
app.directive('lazyload', {
mounted(el, bindings) {
// El-dom element, bindings - directive value
const observer = new IntersectionObserver(([{ isIntersecting }]) = > {
if(isIntersecting) {
observer.unobserve(el)
// indicates that the bound DOM is in the viewable area
el.src = bindings.value
// Display the default image when the image load error occurs
el.onerror = () = > {
el.src = defaultImg
}
}
}, {
threshold: 0
})
/ / to monitor the dom
observer.observe(el)
}
})
}
}
Copy the code
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import directUI from '@/components/index.js'
createApp(App).use(directUI).mount('#app')
Copy the code
- Use in components
<img v-lazyload Alt ="" /> </template>Copy the code