Skip to the code

Lazy-load images

The tea shop's catalog page has dozens of tea photos, and most of them are far down the page. Write lazyLoad(images, options) so a photo loads only when it gets close to the screen. images is a list of <img> elements. Each one to load later has its address in data-src, and may have a data-srcset too; images without a data-src are left alone.

Watch them with one IntersectionObserver whose rootMargin is options.rootMargin, or "200px" when that isn't given, so a photo starts loading a little before it scrolls into view. When an image comes into view, set its srcset from data-srcset (if it has one) and its src from data-src, remove both data- attributes, and stop watching it.

An observer reports every image it starts watching, in view or not, so check isIntersecting before loading one. Where IntersectionObserver doesn't exist, load every image at once. Return a function that stops watching the images that haven't loaded yet.

// <img alt="Oolong" data-src="/teas/oolong.jpg" data-srcset="/teas/oolong-480.jpg 480w, /teas/oolong-960.jpg 960w">
const stop = lazyLoad(document.querySelectorAll("img"));
// When the oolong photo comes within 200px of the screen, it becomes:
// <img alt="Oolong" src="/teas/oolong.jpg" srcset="/teas/oolong-480.jpg 480w, /teas/oolong-960.jpg 960w">

Browsers do this on their own for <img loading="lazy">. A script like this one is for when you want to choose how far ahead photos load, which loading="lazy" doesn't let you set.

What the tests check

  1. watches the images that have a data-src, with one observer and a 200px margin
    const io = useIntersection();
    lazyLoad(document.querySelectorAll("img"));
    const observers = io.observers();
    expect(observers).toHaveLength(1);
    expect(observers[0].options.rootMargin).toBe("200px");
    expect(observers[0].targets.map((img) => img.alt)).toEqual(["Green tea", "Oolong", "Black tea"]);
    
  2. a photo gets its src only when it comes into view, not from the first report that it's out of view
    const io = useIntersection();
    const [green, oolong, black] = document.querySelectorAll("img");
    lazyLoad(document.querySelectorAll("img"));
    await flush();
    expect([green, oolong, black].map((img) => img.getAttribute("src"))).toEqual([null, null, null]);
    io.enter(black);
    expect(black.getAttribute("src")).toBe("/teas/black.jpg");
    expect([green, oolong].map((img) => img.getAttribute("src"))).toEqual([null, null]);
    
  3. copies data-srcset to srcset, and takes the data- attributes off
    const io = useIntersection();
    const [green, oolong] = document.querySelectorAll("img");
    lazyLoad(document.querySelectorAll("img"));
    io.enter(oolong);
    expect(oolong.getAttribute("src")).toBe("/teas/oolong.jpg");
    expect(oolong.getAttribute("srcset")).toBe("/teas/oolong-480.jpg 480w, /teas/oolong-960.jpg 960w");
    expect(oolong.hasAttribute("data-src")).toBe(false);
    expect(oolong.hasAttribute("data-srcset")).toBe(false);
    io.enter(green);
    expect(green.hasAttribute("srcset")).toBe(false);
    
  4. stops watching a photo once it's loaded
    const io = useIntersection();
    const [green] = document.querySelectorAll("img");
    lazyLoad(document.querySelectorAll("img"));
    io.enter(green);
    expect(io.observers()[0].targets.map((img) => img.alt)).toEqual(["Oolong", "Black tea"]);
    green.setAttribute("src", "/teas/green-fresh.jpg");
    io.leave(green);
    io.enter(green);
    expect(green.getAttribute("src")).toBe("/teas/green-fresh.jpg");
    
  5. takes another margin
    const io = useIntersection();
    lazyLoad(document.querySelectorAll("img"), { rootMargin: "50px 0px" });
    expect(io.observers()[0].options.rootMargin).toBe("50px 0px");
    
  6. loads every photo at once where IntersectionObserver isn't there
    useIntersection({ supported: false });
    const images = document.querySelectorAll("img");
    lazyLoad(images);
    expect(Array.from(images, (img) => img.getAttribute("src"))).toEqual(["/teas/green.jpg", "/teas/oolong.jpg", "/teas/black.jpg", "/logo.svg"]);
    expect(images[1].getAttribute("srcset")).toBe("/teas/oolong-480.jpg 480w, /teas/oolong-960.jpg 960w");
    expect(images[1].hasAttribute("data-src")).toBe(false);
    
  7. the function it returns stops watching the photos that haven't loaded
    const io = useIntersection();
    const [green, , black] = document.querySelectorAll("img");
    const stop = lazyLoad(document.querySelectorAll("img"));
    io.enter(green);
    stop();
    io.enter(black);
    expect(black.hasAttribute("src")).toBe(false);
    expect(io.observers()[0].disconnected).toBe(true);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).