Intersection Observer: Lazy Loading

Intersection Observer: Lazy Loading in JavaScript: In the old days, to see if an image was on screen, we had to run code every time the user scrolled.

Concept Explanation

In the old days, to see if an image was on screen, we had to run code every time the user scrolled. This was slow and caused "Jank."

The Intersection Observer is high-performance. It tells the browser: "Don't run my code constantly. Just tell me when this specific element enters or leaves the user's view."


Syntax or Core Structure

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            console.log("Element is visible!");
            // Load an image or trigger an animation here
        }
    });
}, { threshold: 0.5 }); // Trigger when 50% of the element is visible

observer.observe(document.querySelector("#big-image"));

Real World Example

Infinite Scroll (Instagram/TikTok): As you scroll down, there is a hidden "Sensor" at the bottom of the list. When that sensor enters the screen, the Intersection Observer triggers a fetch for the next 10 posts.


Best Practices

  • Unobserve: Once you've loaded a "Lazy Image," call observer.unobserve(element) to stop the browser from watching it and save memory.
  • Thresholds: Use an array of thresholds [0, 0.5, 1] to trigger events at multiple points (e.g., just started entering, half-way, fully visible).
  • Root Margin: Use rootMargin: "200px" to start loading images before the user actually reaches them, making the site feel faster.

Practice Exercises

  1. The Fade-In: Create a section. Use Intersection Observer to add a CSS class that fades it in only when the user scrolls down to it.
  2. The Lazy Image: Create an <img> with a data-src attribute. When it enters the screen, move data-src into the real src.
  3. The Video Pauser: Create a video that automatically .play() when visible and .pause() when you scroll away.