Instructor: Lazy loading is a technique that defers loading on non-critical resources at page load time. Instead, these resources are loaded at the time of need.
When it comes to images, the non-critical images are often the same as off-screen images. Lazy loading images can be accomplished by watching the window scroll or resize events and then calculating when an image is in the viewport.
This is the most compatible way of lazy loading images, but there's another way. This can be accomplished via the Intersection Observer API. The Intersection Observer is supported by current versions of Firefox, Chrome, as well as Edge. To get this to work in all other browsers, see the link in the external resources for how to polyfill.
First up, let's add an event listener for our DOMContentLoaded event. Once that fires, let's make an array of all of our images that have the lazy class name. Now we need to check that the window has the IntersectionObserver, as well as IntersectionObserverEntry and our intersectionRatio, which lives on the prototype.
If it does have that, then inside of this block, we'll do let lazy-image-observer = new-intersection-observer with a function with two arguments, entries and observer. For each entry, we want to check to see if it's intersecting or in the viewport.
Then if it is, we want to grab that current entry target and update its source to be the dataset source or update the source set to equal the dataset source set. Then we will remove the class name lazy and then unobserve that current image.
To recap what we've done so far, we've created an array of images that all have the lazy class name. Then we've checked the window to make sure that it's compatible. If it is, we've assigned a new-intersection-observer object to lazy-image-observer.
This works with each entry which describes an intersection change for one observed target element. If it is intersecting, then we modify the image HTML, swapping out a hypothetical placeholder image with the real source.
For each of our images, we actually need to tell our observer what to observe. We're going to for each of our array, and for each one of our images, we're going to use the .observe and pass through our lazy image. This completes the relationship between observers and observes.
Our polyfill, we'll just go on the else block here. With the JS part done, when we create our image HTML, we can place a placeholder image in the source, and the real image source inside of our dataset source.
You may feel the desire to lazy load all of your images, but keep in mind it's recommended to only lazy load images that lie below the fold, which can be difficult, depending on if you're looking at it on a mobile or a laptop. Do an analysis of your website and see what looks best and works best for you.