Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.6 — Observers
JavaScript · Example 3 of 3

MutationObserver: batched records, delivered as a microtask

The three changes made by the script arrived together, after script finished, as one microtask. Setting textContent replaces the <li>'s text node, so it's a childList change on the <li> (seen because of subtree: true), not a characterData change.

Observers let the browser tell you when something changes instead of you checking again and again: IntersectionObserver reports when elements enter or leave view, ResizeObserver when an element's size changes, and MutationObserver when the DOM itself is changed.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write onceVisible(el, fn) that calls fn() the first time el becomes visible, then stops observing.

02

Use a MutationObserver to log New message: <text> whenever an <li> is added to #chat, then add one with code.

Explain it without notes

01

Why are observers better than scroll and resize listeners for visibility and size checks?

02

How would you lazy-load images with IntersectionObserver? What do rootMargin and threshold do?

03

What does MutationObserver report, and when does its callback run?

04

When would you use ResizeObserver instead of CSS container queries?

MutationObserver: batched records, delivered as a microtask

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

script finished
callback with 3 records
  childList: added 1 removed 0
  attributes: class old value: null
  childList: added 0 removed 1
callback with 1 records
  childList: added 1 removed 1