DEV Community

WDSEGA
WDSEGA

Posted on

Component Deep Dive #23: Infinite Scroll - Never Show a Next Page Button Again

Web Component Dictionary v2.0 - 83 Components, Bilingual, Live Preview
Live Demo | Buy on Payhip

Instagram, Twitter, TikTok - no "Next Page" button. They use infinite scroll. Swipe down, content auto-loads. No end.

But if implemented wrong: duplicate content, stuttering, or sudden jumps back to top.

Core: IntersectionObserver + Sentinel

javascript
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) loadMore();
}, { rootMargin: '200px' });
observer.observe(sentinel);

rootMargin: '200px' Is Key

Default fires when element enters viewport - user already hit bottom before loading starts. rootMargin: '200px' fires 200px before viewport edge. Data pre-loads.

Best: 200-400px.

3 Must-Fix Bugs

  1. Duplicate triggers - unobserve during load, observe after
  2. Page jumping - use insertAdjacentHTML('beforeend'), not innerHTML +=
  3. Jump to top on mobile - preserve scrollTop during load

When to Use vs Not

Social feeds ? | E-commerce ?? (use "Load More" button) | Search results ? | Data tables ?

E-commerce: users need to locate specific items. Infinite scroll has no page numbers, can't jump to position.

Virtual List for 10k+ Items

Only render visible area. react-window / vue-virtual-scroller use this principle.

Performance Checklist

  1. rootMargin: 200px - pre-load
  2. unobserve during load - prevent duplicates
  3. insertAdjacentHTML - no re-parse
  4. loading="lazy" on images
  5. will-change: transform - GPU acceleration
  6. Virtual list for >1000 items

Infinite scroll essence: never let users feel they're waiting.


Bilingual version at wdsega.github.io

Top comments (0)