Lazy load images in Preact using Intersection Observer
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).IntersectionObserver
s 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.
- Image component take original Image URL in src props
- Image component replace the original src with data-src
- IntersectionObserver initiates in componentDidMount and uses the
inview
method as a callback. - IntersectionObserver observes the element which is
.image-container
- If
.image-container
is in-view it sets the state with loaded property to true - 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 :)