← All posts

Tutorials

Auto-pager — infinite scroll on any page

A forum, a blog archive, search results — content split across 40 pages with a "Next" link at the bottom. Click, wait, click, wait. Auto-pager does it for you: when you reach the bottom, the rule fetches the next page and appends its content. Infinite scroll on a page that does not have it.

The idea

Every paginated page has two things: a "next" link (often <a rel="next">) and a container with the actual content. Auto-pager:

  1. Detects that you have scrolled near the bottom.
  2. Fetches the next page's HTML via fetch.
  3. Extracts the content container and appends its children to the current one.
  4. Swaps the "next" link for the one from the new page — and repeats.

The rule

The rule's JavaScript — adjust the two selectors at the top to the specific site:

const NEXT = 'a[rel="next"]';
const LIST = '#content';
let loading = false;
addEventListener('scroll', async () => {
  if (loading || !document.querySelector(NEXT)) return;
  if (innerHeight + scrollY < document.body.offsetHeight - 1200) return;
  loading = true;
  const next = document.querySelector(NEXT);
  const html = await fetch(next.href).then(r => r.text());
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const more = doc.querySelector(LIST);
  if (more) document.querySelector(LIST).append(...more.childNodes);
  const nn = doc.querySelector(NEXT);
  nn ? (next.href = nn.href) : next.remove();
  loading = false;
});

Two selectors to tune

How it works

Detecting the bottom

innerHeight + scrollY is the position of the window's bottom edge within the document. When it nears document.body.offsetHeight (with a 1200 px margin), it is time to pull more.

The loading lock

The scroll event fires dozens of times per second. The loading flag guarantees one fetch runs at a time — without it you would append the same page twenty times.

DOMParser

fetch returns raw HTML as text. DOMParser turns it into a queryable document, from which querySelector pulls just the content container — without the new page's header, footer and menu.

Pitfalls

See also

Install JustZix — and scroll instead of clicking "Next".

Rate this post

No ratings yet — be the first.

Try it yourself

Install JustZix and paste any snippet from this article. Two minutes from zero to a working rule across all your devices.

Get JustZix

Features · How it works · Examples · Use cases