IntersectionObserver for Lazy Sections
Lesson 21 of 38 in the JavaScript learning path.
How do I run code when an element scrolls into view?
IntersectionObserver reports when a target element crosses a visibility threshold inside a root. The root is the viewport when you pass null, or a scrollable element when you pass that element. threshold is the fraction of the target that must be visible, from 0 to 1. rootMargin grows or shrinks the root box in pixels or percent, using the same shorthand as a CSS margin.
Use it for lazy sections, analytics beacons, and play-on-view. Each entry has isIntersecting, intersectionRatio, and the target. Unobserve a target after you have handled it once so a long page does not keep firing for a block that already ran. The observer does not fetch an image by itself. Your callback starts that work.
Syntax & Parameters
new IntersectionObserver(callback, { root, threshold: 0.5 });
Example
Interactive preview availableconst style = document.createElement("style");
style.textContent = [
"#section-scroller { height: 140px; overflow: auto; border: 1px solid #cbd5e1; }",
"#section-scroller section { min-height: 120px; padding: 12px; margin: 0 0 8px; background: #f8fafc; }",
"#section-scroller section.is-visible { background: #dcfce7; }"
].join("\n");
document.head.append(style);
const scroller = document.createElement("div");
scroller.id = "section-scroller";
const status = document.createElement("p");
status.id = "seen-status";
status.textContent = "Nothing in view yet";
function makeSection(name, once) {
const section = document.createElement("section");
section.dataset.section = name;
section.dataset.once = once ? "true" : "false";
section.textContent = name;
return section;
}
scroller.append(
makeSection("Routes", false),
makeSection("Queries", true),
makeSection("Blade", false)
);
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const name = entry.target.dataset.section || "section";
if (entry.isIntersecting) {
entry.target.classList.add("is-visible");
status.textContent = name + " is in view (" + entry.intersectionRatio.toFixed(2) + ")";
if (entry.target.dataset.once === "true") {
observer.unobserve(entry.target);
}
} else {
entry.target.classList.remove("is-visible");
}
}
}, {
root: scroller,
rootMargin: "0px",
threshold: 0.5
});
for (const section of scroller.querySelectorAll("[data-section]")) {
observer.observe(section);
}
const add = document.createElement("button");
add.type = "button";
add.id = "add-section";
add.textContent = "Add a section";
add.addEventListener("click", () => {
const section = makeSection("Extra", true);
scroller.append(section);
observer.observe(section);
scroller.scrollTop = scroller.scrollHeight;
});
document.body.append(status, scroller, add);
Expected Output
On load the status names Routes, because that section is at least half visible, and Routes receives is-visible. Scrolling until Queries crosses the threshold names Queries, paints it, then unobserves it. Add a section appends Extra, observes it, and scrolls the box to the bottom.
Line-by-Line Walkthrough
- The style element gives the scroll box a fixed height so later sections start out of view.
- makeSection sets data-section and data-once and uses the section name as its text.
- Queries is marked once so the observer can drop it after the first time it qualifies.
- The observer root is the scroll box. null would mean the viewport instead.
- threshold 0.5 means at least half of the section must be visible inside that root.
- rootMargin is 0px here. A negative bottom margin would shrink the box you have to enter.
- A visible section gains is-visible, and the status names it with the intersection ratio.
- data-once true calls unobserve so that target does not keep reporting.
- A section that leaves the box loses is-visible. The startup loop observes the three sections.
- The button appends Extra, observes it, and scrolls the box so the new section can enter the root.
Common Pitfalls & Security
The callback can fire immediately for anything that is already visible. Do not assume the first call means the visitor scrolled.
- A threshold of 0 fires when a single pixel shows. A large image can start loading before the visitor is near it.
- root must be an ancestor of the target. A root that does not scroll, or overflow visible, never produces a useful intersection.
- Forgetting unobserve leaves the callback running for the life of the page.
- display none and a detached element do not intersect. Observe after the node is in the document.
- rootMargin values are parsed like CSS. A unitless 10 is invalid and the observer throws.
- The ratio is not a security check. Content below the fold is still in the HTML for anyone who views source.
Best Practices & Modern Standards
Observe the smallest element that means "start this work", not a huge wrapper that is always a little bit on screen. Use a threshold of 0 for a beacon that should fire as soon as the block arrives, and a higher threshold when the visitor should actually see the section.
Disconnect the observer when you leave the page in a single-page shell, and unobserve targets you will not use again. Keep the callback short. Start a fetch or a render from it, and do not do layout reads in a loop if you can store the decision on the element.
Real-World Use
A lesson page stacks Routes, Queries, and Blade inside a scroll box. Queries records one view when half of it is visible, then stops watching so the beacon cannot double count as the reader moves on. Extra sections added later join the same observer.
Frequently Asked Questions
When does the callback run?
It runs once when you observe a target that already meets the threshold, and again when a target crosses that threshold in either direction.
What is threshold?
A number from 0 to 1, or an array of those numbers. 0.5 means half of the target is visible inside the root. 1 means the whole target is visible.
How do I watch the viewport?
Pass root null, or omit root. The browser then uses the viewport. Pass an element only when that element is the scroll container.
Does this lazy load an image by itself?
No. The callback is where you set img.src or start a fetch. For plain images, the loading attribute is often enough, and the observer is for work that attribute cannot express.