Shopify Customization

Implementing Infinite Scroll in Shopify

By Mohd Baquir Qureshi
Continuous data loading

Classic pagination creates friction. In modern e-commerce, customers expect a seamless, infinite browsing experience on mobile devices. Here's a lightweight Vanilla JS method to implement infinite scroll on Shopify Collection pages.

The Fetch API Approach

Instead of relying on heavy jQuery plugins, we can use the native Fetch API to grab the next page's HTML, parse it, and append the products to the current grid.


document.addEventListener('DOMContentLoaded', function() {
  const productGrid = document.querySelector('.product-grid');
  let nextUrl = document.querySelector('.pagination .next a')?.href;
  let isLoading = false;

  window.addEventListener('scroll', () => {
    if (isLoading || !nextUrl) return;
    
    const scrollPosition = window.innerHeight + window.scrollY;
    const triggerPoint = document.body.offsetHeight - 800;

    if (scrollPosition >= triggerPoint) {
      loadNextPage();
    }
  });

  async function loadNextPage() {
    isLoading = true;
    try {
      const response = await fetch(nextUrl);
      const htmlText = await response.text();
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlText, 'text/html');
      
      const newProducts = doc.querySelectorAll('.product-grid .product-item');
      newProducts.forEach(item => productGrid.appendChild(item));
      
      nextUrl = doc.querySelector('.pagination .next a')?.href;
    } catch (error) {
      console.error('Error loading next page:', error);
    }
    isLoading = false;
  }
});

Why this works well

By parsing the HTML response, you do not need to hit the Storefront API or deal with complex JSON manipulation. You simply extract the existing rendered HTML blocks (which already include image tags, pricing, and app integrations like review stars) and append them to the DOM.