Traditional implementation
The traditional image lazy loading implementation is mainly by listening to the container’s OnScroll event, in the event callback through the getBoundingClientRect method to get the coordinate of the element from the upper left corner of the window. Then, according to the width and height of the screen to determine whether the element and window intersection.
But this approach has a major drawback: the OnScroll event is a frequently executed event with a lot of computation, and since JS is threaded, it affects the rendering performance of the page.
IntersectionObserver implementation
IntersectionObjser provides an asynchronous way to observe the intersecting status of target elements and their ancestors or Windows.
Implementation steps
HTML, take VUE as an example
<div class="container"> <! <div class="skeleton" ref="lazyImage" v-if="! > this is the skeleton screen </div> <! <img SRC ="url" v-else /> </div>Copy the code
js
New Vue({data() {return {showImage: false, url: 'intersection ', intersection: LazyImage Mounted () {this. Intersection = new IntersectionObserver(entries => {// Because we only want to check one element, So if the 0 const current = entries[0] // intersectionRatio > 0, Said the current element with the view have crossed the if (current) intersectionRatio > 0) {/ / close to monitor this. Intersection computes?. Disconnect () / / create a Image object const Image = Image.onload = () => {this.showimage = true; new Image() image.src = this.url; }}}) / / to start listening to the dom elements. This intersection computes. Observe (this. $refs. LazyImage)}})Copy the code