A Vue Directive That Lazy-Loads Only in View, With a Scroll Fallback
Cutting initial render cost is crucial for performance budgets; this directive offers a drop-in solution that works across browsers without per-list cleanup code. But it's only a timing optimization: oversized assets still demand proper compression and responsive sizing before this is effective.
Lazy loading is standard practice for cutting initial payload: only fetch and render content as it scrolls into the viewport. IntersectionObserver does this asynchronously, but not all browsers support it. The usual fallback is scroll events, which trigger too often and cause layout thrashing unless throttled.
A Vue developer has packaged both strategies into a single directive, v-lazy. When the observer is available, it registers a callback and stops after the element becomes visible. Otherwise, it attaches a throttled scroll listener that checks visibility via getBoundingClientRect, then removes itself. The directive also marks elements as loaded to avoid duplicate loads and cleans up listeners on unmount to prevent leaks.
The directive accepts options like src, container, rootMargin, threshold, and an onLoad callback. A WeakMap stores cleanup functions. Lazy loading only defers requests; it does not shrink assets. The article reminds us that images larger than a few megabytes still need compression and format conversion (WebP/AVIF) before lazy loading becomes a last line of defense.
The WeakMap-based cleanup pattern in the directive is a clean way to handle per-element teardown, avoiding the common pitfall of leaked observers in long lists.
The fallback from IntersectionObserver to throttled scroll is a practical compromise: it keeps the API consistent while accepting a performance cost on old browsers, which are a shrinking but real segment.
The final note that lazy loading doesn't fix large assets is a necessary corrective; many teams over-rely on lazy loading and skip proper image optimization.