sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEIntermediate3 min read

When is IntersectionObserver useful?

IntersectionObserver reports when elements intersect a viewport or another root.

JavaScript#browser#performance
THE ANSWER / PLAIN ENGLISH

The idea to remember.

IntersectionObserver reports when elements intersect a viewport or another root. It can replace continuous scroll calculations for lazy loading, visibility tracking, and entering-view animations.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: delegate one listener

01 / BEGINNER

A parent can handle events from matching children.

JAVASCRIPT / EXAMPLE
document.querySelector('#list').addEventListener('click', event => {
  const button = event.target.closest('button[data-id]');
  if (button) console.log(button.dataset.id);
});

Intermediate: respect request lifecycles

02 / INTERMEDIATE

Abort a pending request when it is no longer needed.

JAVASCRIPT / EXAMPLE
const controller = new AbortController();
fetch('/api/items', { signal: controller.signal });
// When the user navigates away:
controller.abort();

Real scenario: safe persisted preferences

03 / REAL SCENARIO

Validate stored data instead of assuming it is trustworthy.

JAVASCRIPT / EXAMPLE
function readTheme() {
  const stored = localStorage.getItem('theme');
  return stored === 'dark' ? 'dark' : 'light';
}
function saveTheme(theme) {
  if (theme === 'dark' || theme === 'light') localStorage.setItem('theme', theme);
}

Try it in your own words.

Explain when is IntersectionObserver useful without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse JavaScript study guides ↗
← Back to question library

Have something
in mind?

Start a conversation