DEV Community

WDSEGA
WDSEGA

Posted on • Originally published at wdsega.github.io

Component Deep Dive #7: Pagination — Loading 10,000 Records One Page at a Time

This component is from Web Component Dictionary v2.0 — 83 components, bilingual, live preview, zero dependencies.

You search "phone case" and get 12,847 results. Rendering them all freezes the browser. Pagination solves this — but it's full of pitfalls.

The Ellipsis Algorithm

The hardest part isn't styling — it's knowing when to show "...". When total pages exceed visible pages, middle pages fold into ellipsis:

function getPageNumbers(current, total, visible = 5) {
  let pages = [];
  let start = Math.max(1, current - Math.floor(visible / 2));
  let end = Math.min(total, start + visible - 1);
  start = Math.max(1, end - visible + 1);
  if (start > 1) { pages.push(1); if (start > 2) pages.push('...'); }
  for (let i = start; i <= end; i++) pages.push(i);
  if (end < total) { if (end < total - 1) pages.push('...'); pages.push(total); }
  return pages;
}
Enter fullscreen mode Exit fullscreen mode

Common Pitfalls

  1. Page overflow: User types ?page=999 — always validate bounds
  2. Race conditions: Fast clicking sends multiple requests — use AbortController
  3. SEO: Search engines may not execute JS — provide rel="next"/rel="prev"

URL Sync

Users refreshing or sharing should return to the same page:

const params = new URLSearchParams(window.location.search);
let currentPage = parseInt(params.get('page')) || 1;
Enter fullscreen mode Exit fullscreen mode

Complete Working Code

The full implementation includes prev/next buttons with disabled states, active page highlighting, and ellipsis folding — all in a single HTML file with no dependencies.

Variants

  • Infinite scroll: Intersection Observer loads next page automatically
  • Page jump input: Let users type a number to jump
  • Per-page selector: Choose 10/20/50 items per page
  • Mobile simplification: Show only "3/12" on small screens

Web Component Dictionary v2.0 — 83 components, 8 categories, bilingual, $1.99. Live preview

Top comments (0)