# Intersection Observer and Mutation Observer

> What is the Intersection Observer API? How does it differ from scroll event listeners?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-intersection-observer
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is the Intersection Observer API? How does it differ from scroll event listeners?

## Answer

The Intersection Observer API asynchronously observes when a target element enters or exits a viewport. It is far more performant than scroll event listeners because:

- It runs off the main thread (no layout thrashing)
- The browser batches observations
- No manual scroll position calculations needed

Mutation Observer observes DOM changes (child additions, attribute changes, text modifications).

Use cases:

- IntersectionObserver: lazy image loading, infinite scroll, animating elements on scroll, ad impression tracking
- MutationObserver: observing third-party DOM changes, auto-save on content edits

**IntersectionObserver while scrolling. Change threshold and rootMargin, or keep observing, under Tweak.**

1. **observe() reports immediately**: One initial entry per target.
2. **Callbacks only on crossings**: Nothing runs while targets stay on the same side of a threshold.
3. **rootMargin**: Extends the root so loading starts before the element is visible.
4. **unobserve**: Lazy loading stops watching an element once it has loaded.

## Code examples

### Lazy Loading Images

```
const imageObserver = new IntersectionObserver(
  (entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.classList.remove('lazy');
        observer.unobserve(img);
      }
    });
  },
  {
    rootMargin: '100px 0px',
    threshold: 0
  }
);

document.querySelectorAll('img[data-src]').forEach(img => {
  imageObserver.observe(img);
});

// Infinite scroll
const loadMoreObserver = new IntersectionObserver(entries => {
  if (entries[0].isIntersecting) {
    loadNextPage();
  }
});

loadMoreObserver.observe(document.querySelector('#sentinel'));
```

rootMargin pre-loads images before they enter view. observer.unobserve() stops watching once the image is loaded.

### MutationObserver

```
const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      console.log('Children added:', mutation.addedNodes.length);
    }
    if (mutation.type === 'attributes') {
      console.log(`Attribute '${mutation.attributeName}' changed`);
    }
  });
});

observer.observe(document.querySelector('#content'), {
  childList: true,
  attributes: true,
  subtree: true
});

// Always disconnect to prevent memory leaks
observer.disconnect();

// Detect when a third-party widget loads
const chatObserver = new MutationObserver((mutations, obs) => {
  const chat = document.querySelector('.chat-widget');
  if (chat) {
    initListeners(chat);
    obs.disconnect();
  }
});
chatObserver.observe(document.body, { childList: true, subtree: true });
```

MutationObserver receives batched MutationRecord objects. disconnect() must be called to stop observation and avoid memory leaks.

## Key points

- IntersectionObserver is supported in all modern browsers; no IE11 support
- threshold: \[0, 0.25, 0.5, 0.75, 1\] fires at each 25% intersection increment
- MutationObserver fires at end of microtask with batched mutations
- Always call disconnect() when done to prevent memory leaks

## Common follow-up questions

- What is the performance difference between IntersectionObserver and scroll events?
- What does rootMargin do in IntersectionObserver options?
- How would you implement infinite scroll with IntersectionObserver?

## Interview tips

- The performance argument (off main thread) is the main selling point
- Show lazy loading implementation - the most common real-world use case
- MutationObserver shows deep DOM knowledge - a differentiator

## Concepts covered

IntersectionObserver, MutationObserver, Lazy Loading, Infinite Scroll

Previous: [Tagged Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates) · Next: [Async Iterators and for await...of](https://www.internhack.in/learn/interview/javascript-interview/js-async-iterators) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Advanced Object Patterns and Mixins](https://www.internhack.in/learn/interview/javascript-interview/js-object-patterns)
- [ES Modules vs CommonJS](https://www.internhack.in/learn/interview/javascript-interview/js-modules-advanced)
- [Promise Combinators](https://www.internhack.in/learn/interview/javascript-interview/js-promise-combinators)
- [Variables: var, let, const](https://www.internhack.in/learn/interview/javascript-interview/js-var-let-const)
- [Data Types & Type Checking](https://www.internhack.in/learn/interview/javascript-interview/js-data-types)
- [Operators & Short-Circuit Evaluation](https://www.internhack.in/learn/interview/javascript-interview/js-operators-short-circuit)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
