Vanilla JavaScript Projects

Project 16, Modern UI

Infinite Scroll Feed

Scroll and new posts keep arriving. Images load just before they come into view, and the counter tracks which posts you actually saw.

Main API
Intersection Observer
Images
Lorem Picsum
Dependencies
None
Your browser
Checking

Your feed

Scroll down. The feed stops after 10 pages so you can see the end state.

0 posts loaded0 seen

How it works

  1. Watch a sentinelAn empty element sits under the last post. When it gets within 600 px of the screen, the next page loads.
  2. Lazy load imagesA second observer swaps data-src into src only when an image is about to be seen.
  3. Track viewsA third observer with threshold 0.6 marks each post as seen the first time most of it is visible.
const loadMore = new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) fetchNextPage();
}, { rootMargin: "600px" });           // start 600px before the end
loadMore.observe(document.querySelector("#sentinel"));

const lazy = new IntersectionObserver((entries) => {
  for (const e of entries) if (e.isIntersecting) {
    e.target.src = e.target.dataset.src;  // swap in the real image
    lazy.unobserve(e.target);
  }
}, { rootMargin: "300px" });