Typically we need to write JavaScript to handle image lazy loading, often in the form of a scroll handler or intersection observer:
<img class="lazyload" src="placeholder.jpg" data-src="pine.png">
<script>
document.addEventListener('scroll', () => {
const scrollTop = window.pageYOffset;
const lazyImages = document.querySelectorAll('.lazyload');
lazyImages.forEach(img => {
if (img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazyload');
}
});
});
</script>
But now there's an experimental feature where you can simply use loading="lazy"
to achieve the same result:
<img src="pine.jpg" loading="lazy">
With the loading attribute set to lazy
, the browser will do all the heavy lifting and will only load the image sources once the user scrolls near the image. We don't even need to use placeholder images to keep our markup valid!
As of now, this feature is supported in Chrome, Edge, and Firefox. Come on, Safari - get with it!
Here's a video using this in action:
Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok
Top comments (0)