{
    "slug": "intersection_observer",
    "term": "Intersection Observer API",
    "category": "frontend",
    "difficulty": "intermediate",
    "short": "A browser API that efficiently detects when elements enter or leave the viewport — replacing scroll event listeners for lazy loading, infinite scroll, and animation triggers.",
    "long": "The Intersection Observer API calls a callback when a target element intersects with a root element (or the viewport). It is asynchronous and off the main thread — far more efficient than scroll event listeners which fire on every pixel of scroll. Use cases: lazy loading images, infinite scroll, triggering CSS animations when elements enter view, sticky header detection, and ad impression tracking. threshold (0.0-1.0) defines how much of the element must be visible to trigger, rootMargin pre-loads before the element is fully visible.",
    "aliases": [
        "IntersectionObserver",
        "lazy loading",
        "scroll detection"
    ],
    "tags": [
        "frontend",
        "javascript",
        "performance"
    ],
    "misconception": "Scroll event listeners are fine for detecting element visibility — scroll events fire hundreds of times per second on the main thread; Intersection Observer is asynchronous and does not block rendering.",
    "why_it_matters": "Scroll event listeners for visibility detection cause main thread jank — Intersection Observer is the standard, performant replacement that does not affect scroll performance.",
    "common_mistakes": [
        "Not disconnecting the observer after the element is loaded — the observer keeps running unnecessarily.",
        "threshold: 1.0 for lazy loading — waits until the element is fully visible; use 0.1 to preload before it appears.",
        "No rootMargin for lazy loading — images load exactly as they enter the viewport; add '200px' margin to preload ahead.",
        "Using Intersection Observer for precise scroll position — it only fires at intersection thresholds, not on every pixel."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "lazy_loading_images",
        "web_vitals",
        "render_blocking_resources",
        "preload_prefetch"
    ],
    "prerequisites": [
        "lazy_loading_images",
        "web_vitals",
        "js_event_loop"
    ],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API"
    ],
    "bad_code": "// Scroll event — main thread, fires hundreds of times per second:\nwindow.addEventListener('scroll', () => {\n    document.querySelectorAll('img[data-src]').forEach(img => {\n        const rect = img.getBoundingClientRect();\n        if (rect.top < window.innerHeight) {\n            img.src = img.dataset.src; // Expensive DOM query on every scroll event\n        }\n    });\n});",
    "good_code": "// Intersection Observer — async, efficient:\nconst observer = new IntersectionObserver((entries) => {\n    entries.forEach(entry => {\n        if (entry.isIntersecting) {\n            const img = entry.target;\n            img.src = img.dataset.src;\n            observer.unobserve(img); // Stop observing once loaded\n        }\n    });\n}, { rootMargin: '200px', threshold: 0.1 }); // Preload 200px before visible\n\ndocument.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));",
    "quick_fix": "Replace scroll event listeners with IntersectionObserver for lazy loading, infinite scroll, and animation triggers — it runs off the main thread with zero scroll performance impact",
    "severity": "medium",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/intersection_observer",
        "html_url": "https://codeclaritylab.com/glossary/intersection_observer",
        "json_url": "https://codeclaritylab.com/glossary/intersection_observer.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Intersection Observer API](https://codeclaritylab.com/glossary/intersection_observer) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/intersection_observer"
            }
        }
    }
}