Learning Tips | Published Nov 17, 2026 | 8 min read

JavaScript IntersectionObserver: Observe Elements Near the Viewport

Learn JavaScript IntersectionObserver root, rootMargin, thresholds, lazy loading, load-more sentinels, cleanup, and accessible fallbacks.

Diagram shows a viewport root, expanded rootMargin preloading region, and a target image crossing a threshold to trigger an observer callback

IntersectionObserver asynchronously reports when an element crosses visibility thresholds relative to a viewport or scroll container. Learn how to use it for lazy loading and load-more sentinels, tune rootMargin, and clean up observers.

Pages often need to react when an element approaches the visible area: load an image, reveal a section, or request the next batch of items. Repeated scroll handlers that measure element positions can be hard to coordinate. IntersectionObserver lets the browser asynchronously report when a target crosses a configured visibility threshold.

Observe a target near the viewport

With the default root, the browser viewport is used. The callback receives entries for targets whose intersection crossed one of the configured thresholds.

const images = document.querySelectorAll("img[data-src]");

const imageObserver = new IntersectionObserver((entries, observer) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;

    const image = entry.target;
    image.src = image.dataset.src;
    image.removeAttribute("data-src");
    observer.unobserve(image);
  }
}, {
  root: null,
  rootMargin: "200px 0px",
  threshold: 0
});

images.forEach((image) => imageObserver.observe(image));

The positive bottom root margin expands the effective root so images can start loading before they enter the viewport. Tune it to the page and network behavior; a very large margin may trigger many unnecessary downloads. For images, native loading="lazy" may be simpler when custom behavior is not required.

Understand root, rootMargin, and threshold

The root is either the viewport or an ancestor scroll container that contains the target. A positive rootMargin expands the root bounds; a negative value shrinks them. The threshold option is a ratio from 0 to 1. With threshold 0, the callback can run as soon as even a small part intersects. An array such as [0, 0.5, 1] requests notifications as visibility crosses those ratios.

This API reports geometric intersection with the root. It is not a pixel-perfect test that proves the element is unobscured or actually perceived by a person. Use it for visibility-triggered behavior, not as a security or precise attention measurement.

Use a sentinel for load more

A sentinel is a small element after a list. When it intersects the scroll area, request another page, then observe it again after adding results. Guard against duplicate requests and stop observing when no more content remains.

let loading = false;
let hasMore = true;

const observer = new IntersectionObserver(async ([entry]) => {
  if (!entry.isIntersecting || loading || !hasMore) return;

  loading = true;
  try {
    const page = await fetchNextPage();
    appendItems(page.items);
    hasMore = page.hasMore;
    if (!hasMore) observer.unobserve(entry.target);
  } finally {
    loading = false;
  }
}, { rootMargin: "300px 0px" });

observer.observe(document.querySelector("#load-more-sentinel"));

Keep an ordinary button or other accessible way to request more items when needed. Infinite loading can make keyboard navigation, page-footer access, and restoration of scroll position harder. Ensure newly inserted content is announced or otherwise discoverable in the interface.

Clean up and handle unsupported cases

Call unobserve(target) when one target no longer needs observation, or disconnect() when the whole component is removed. This avoids stale callbacks and retained elements. For browsers outside the project’s supported range, feature-detect IntersectionObserver and use a sensible fallback such as loading all content or a button-driven action.

The callback can contain multiple entries, so do not assume it handles only one target. If loading work is asynchronous, track in-flight requests and errors separately. Re-observe only after the component has a target that still needs to be monitored.

Test behavior, not just the callback

  • Test a custom scroll root as well as the viewport.
  • Check rootMargin behavior near each edge and test slow networks.
  • Confirm an image fallback remains available if JavaScript or the API is unavailable.
  • Verify load-more controls work with keyboard and do not request duplicate pages.
  • Remove components and confirm observers stop watching detached targets.

IntersectionObserver is a useful signal for proximity and visibility thresholds, not a complete replacement for every scroll interaction. Choose a conservative margin, keep loading state guarded, and include a functional fallback for the actual interface.

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance