typestar

Observers in JavaScript

IntersectionObserver and MutationObserver watch without polling.

function lazyLoad(images) {
  const observer = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      if (!entry.isIntersecting) continue;
      const image = entry.target;
      image.src = image.dataset.src;
      observer.unobserve(image);
    }
  }, { rootMargin: "200px", threshold: 0 });

  images.forEach((image) => observer.observe(image));
  return () => observer.disconnect();
}

function watchList(list, onChange) {
  const observer = new MutationObserver((records) => {
    const added = records.flatMap((record) => [...record.addedNodes]);
    if (added.length) onChange(added.length);
  });
  observer.observe(list, { childList: true, subtree: true });
  return observer;
}

How it works

  1. An intersection observer fires when visibility changes.
  2. rootMargin triggers before the element is on screen.
  3. A mutation observer reports DOM changes in batches.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
657
Tokens
174
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 1 of 2 in Watching & drawing, step 9 of 13 in The browser.

← Previous Next →