Why should Intersection Observer still observe if the image and animation already trigger?

(This is the sequel post of https://justanotherwebdev.com/posts/intersection-observer-part-2/ )

Hello comrades, let me tell you some secret, we successfully implemented both lazy load and animation, make the user experience nicer but we haven’t care the performance of the website. Remember - every single elements count. What if we have hundreds of elements that are rely on intersectionObserver without optimization.

Let start a look a look at previously created codepen and optimize it. Shall we?

Let’s add the console.log(entry) and see what is going on behind the scene.

When we scrolled forth and back, the intersectionObserver still triggered and run the javascript code inside the function.

Image in a image block

Let’s take a look, how we can optimize it?

It is where another important parameters come in, that is the observer parameter in the second place.

const observer = new IntersectionObserver((entries, observer) => {})

In the observer , there is function called unobserve(); to make the intersection observer to stop observing the element. It take one argument and it is the element itself.

const observer = new IntersectionObserver((entries, observer) => {
			entries.forEach(entry => {
					if (entry.isIntersecting) {
              console.log(entry)
							// Change the image src to imageURL
							image.classList.add('active');
              observer.unobserve(image)
					}
			});
	}, {});

Now we have stop intersection observer keep triggering and optimize our code.

Here is the final codepen for your reference.

https://codepen.io/starryskadi/pen/yLrYeKg

Happy Hacking!

Copyright © 2024, JUST ANOTHER WEB DEV.