AD
Infinite Scroll on Shopify Collection Pages, No App, Custom Code
In this example, we will add infinite scroll to the Shopify Dawn theme, but the approach works on any Shopify theme.
Steps
- In the assets folder, create a file namded as:
infinite-scroll.js- Paste the following code in that file:
class InfiniteScroll extends HTMLElement {
constructor() {
super();
this.anchor = this.querySelector("a");
if (!this.anchor) return;
this.observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.loadNextPage();
}
});
});
this.observer.observe(this);
}
async loadNextPage() {
this.observer.disconnect();
this.anchor.style.display = "flex";
this.anchor.innerText = "Loading...";
const url = this.anchor.getAttribute("href");
if (!url) return;
try {
const response = await fetch(url);
const text = await response.text();
const html = new DOMParser().parseFromString(text, "text/html");
// Grab the product grid from the next page
const newGrid = html.querySelector("[data-product-grid]");
const grid = document.querySelector("[data-product-grid]");
if (newGrid && grid) {
Array.from(newGrid.children).forEach((child) => {
grid.appendChild(child);
});
}
// Handle next infinite scroll
const newInfinite = html.querySelector("infinite-scroll");
if (newInfinite) {
this.replaceWith(newInfinite);
} else {
this.remove();
}
} catch (err) {
console.error("InfiniteScroll error:", err);
}
this.anchor.style.display = "none";
this.anchor.innerText = "";
}
}
customElements.define("infinite-scroll", InfiniteScroll);
- Then go to
main-collection-product-grid.liquidand locate product grid, add the following attribute to the product grid
data-product-grid
- Then under the product grid, add the following code:
<infinite-scroll style="display: flex; justify-content: center;">
{%- if paginate.next -%}
<a style="color: currentColor; text-decoration: none; pointer-events: none;" href="{{ paginate.next.url }}§ion_id={{ section.id }}"></a>
{%- endif -%}
</infinite-scroll>
- Then comment out the original pagination by adding comment tags at the start and end like this:
{% comment %}
{%- if paginate.pages > 1 -%}
{% render 'pagination', paginate: paginate, anchor: '' %}
{%- endif -%}
{% endcomment %}
- Then at the end of head tag in
theme.liquid, add this line to attach the asset the we created:
<script src="{{ 'infinite-scroll.js' | asset_url }}" defer="defer"></script>
Video Tutorial
Watch the step-by-step video tutorial here:
Reviews
☆☆☆☆☆ No reviews yet
AD
