Tips and Tricks #42: Use Intersection Observer for Lazy Loading

Load images and content only when they enter the viewport for faster initial page loads.

Code Snippet

// Create observer once
const observer = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.classList.remove('lazy');
        observer.unobserve(img);
      }
    });
  },
  { rootMargin: '50px' } // Load 50px before visible
);

// Observe all lazy images
document.querySelectorAll('img.lazy').forEach((img) => {
  observer.observe(img);
});

// HTML: 

Why This Helps

  • Reduces initial page load by 40-60%
  • Saves bandwidth for users who don’t scroll
  • Native browser API, no library needed

How to Test

  • Check Network tab for deferred image loads
  • Measure LCP improvement with Lighthouse

When to Use

Image galleries, infinite scroll, below-the-fold content, heavy landing pages.

Performance/Security Notes

Use rootMargin to preload slightly before visible. Provide placeholder dimensions to prevent layout shift.

References


Try this tip in your next project and share your results in the comments!


Discover more from Byte Architect

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.