Lazy load images in Preact using Intersection Observer

Ashok Vishwakarma
Mar 11 · 2 min read

We love Preact for its tiny size and capabilities which makes it an ideal choice for smaller web applications.

Intersection Observer

Making this visibility test more efficient is what IntersectionObserver was designed for, and it’s landed in Chrome 51 (which is, as of this writing, the beta release). IntersectionObservers let you know when an observed element enters or exits the browser’s viewport.

To know more about Intersection Observer please check out the awesome article written by Surma on Google Web Fundamentals

Which browsers are supported

Most of the modern browsers support Intersection Observer out of the box.

Update: Check latest support details https://caniuse.com/#search=Intersection

If you still need support for older browsers and IE there is a well written and documented polyfill available on Github in the w3c repo, find the link below.

The Image Component in Preact

To enable lazy loading for images the best approach is to create an Image component in Preact and use the same instead of the img tag.

SCSS for .image-container

.image-container{
position: relative;
.loader{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
&.hidden {
display: none;
}
}
}

Uses of the Image component

<Image src={data.image} />

How does it work?

The following happens when you use the Image component instead of the img tag.

  1. Image component take original Image URL in src props
  2. Image component replace the original src with data-src
  3. IntersectionObserver initiates in componentDidMount and uses theinview method as a callback.
  4. IntersectionObserver observes the element which is .image-container
  5. If .image-container is in-view it sets the state with loaded property to true
  6. Which shows the image and also hide the loader.

Conclusion

Lazy loading can make the app load fast and provide a better user experience.


Share this among your friends and also don’t forget to clap :)

Ashok Vishwakarma

Written by

@GoogleDevExpert — #WebTechnologies & @angular | #Principal #Architect at @Naukri | #Entrepreneur | #TechEnthusiast | #Speaker

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade