snippetjavascriptModeratepending
IntersectionObserver -- lazy loading and infinite scroll
Viewed 0 times
IntersectionObserverlazy loadinfinite scrollviewportvisibility
browser
Problem
Need to detect when elements enter/leave the viewport for lazy loading images, infinite scroll, or scroll-triggered animations. Scroll event listeners are expensive and cause jank.
Solution
Use IntersectionObserver API for performant visibility detection. The browser handles the intersection math off the main thread.
Code Snippets
Lazy loading and infinite scroll
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
},
{ rootMargin: '200px' }
);
document.querySelectorAll('img[data-src]').forEach((img) => {
observer.observe(img);
});
// Infinite scroll
const sentinel = document.getElementById('sentinel');
new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadNextPage();
}).observe(sentinel);Revisions (0)
No revisions yet.