DEV Community

Cover image for Vanilla JavaScript Infinite Scroll using WordPress REST API
Cadu de Castro Alves
Cadu de Castro Alves

Posted on

Vanilla JavaScript Infinite Scroll using WordPress REST API

This pen is a real example of how to build an Infinite Scroll in Vanilla JavaScript. I've used Fetch API, Intersection Observer API, and WordPress REST API to fetch posts. Feel free to fork, use, and modify this code.

Top comments (1)

Collapse
 
stackedboost profile image
Peter Hallander

Nice pattern — combining Intersection Observer with the WP REST API is exactly the right approach for lazy-loading content.

One thing worth adding: if you append &_embed to the REST endpoint, WordPress includes the featured image and author data in the same response, so you avoid a second request per post. The embedded image is at post._embedded['wp:featuredmedia']?.[0]?.media_details?.sizes?.medium?.source_url. Saves a round-trip per item, which matters once your scroll depth gets a few pages in.

I ran into this while building a Shopify app (WP Simple WordPress Feed on the Shopify App Store) that syncs WordPress posts into a Shopify storefront block. We hit the same issue — _embed was the fix for featured images. We also added a server-side 10-minute TTL cache in front of the WP REST endpoint so the storefront isn't hammering WordPress on every page load.

The Intersection Observer approach for triggering loads is spot on. We use the same API on the Shopify side for viewport-based prefetching of navigation links — same pattern, different use case.