如何为Shopify博客页面添加加载更多按钮(替代分页)
Shopify博客页面实现“加载更多”按钮替代分页
步骤1:调整模板结构,替换分页为加载更多按钮
修改你的博客section代码,完成两处核心调整:
给文章列表容器添加唯一class(方便JS定位):
找到所有包含{%- for article in blog.articles -%}的grid容器,添加blog-articles-gridclass,示例:<div class="grid grid-cols-1 {% if section.settings.view == 'grid' %}grid-cols-2 md:grid-cols-{{ section.settings.show_item_per_row | minus: 1 }} lg:grid-cols-{{ section.settings.show_item_per_row }}{% endif %} gap-8 blog-articles-grid"> {%- for article in blog.articles -%} {% render 'article-card', article: article, view: item.view %} {% endfor %} </div>替换原分页组件为加载更多按钮:
删除原有的{% render 'pagination', paginate: paginate %},替换为以下代码:{%- if paginate.pages > 1 -%} <div class="flex justify-center my-7 lg:my-16"> <button class="load-more-btn" data-next-url="{{ paginate.next.url }}">加载更多</button> </div> {%- endif -%}
步骤2:添加AJAX加载的JavaScript代码
在主题中添加以下JS(可以放在该section末尾,或theme.liquid的</body>标签前):
document.addEventListener('DOMContentLoaded', function() { const loadMoreBtn = document.querySelector('.load-more-btn'); const articlesGrid = document.querySelector('.blog-articles-grid'); if (!loadMoreBtn || !articlesGrid) return; loadMoreBtn.addEventListener('click', async function() { const nextUrl = this.dataset.nextUrl; if (!nextUrl) return; // 禁用按钮防止重复点击 this.disabled = true; this.textContent = '加载中...'; try { const response = await fetch(nextUrl); if (!response.ok) throw new Error('请求失败'); const html = await response.text(); const tempContainer = document.createElement('div'); tempContainer.innerHTML = html; // 提取新文章卡片并插入到列表 const newArticleCards = tempContainer.querySelectorAll('.article-card'); newArticleCards.forEach(card => articlesGrid.appendChild(card)); // 更新下一页链接,没有更多则隐藏按钮 const newNextUrl = tempContainer.querySelector('.load-more-btn')?.dataset.nextUrl; if (newNextUrl) { this.dataset.nextUrl = newNextUrl; this.disabled = false; this.textContent = '加载更多'; } else { this.style.display = 'none'; } } catch (err) { console.error(err); this.disabled = false; this.textContent = '加载失败,重试'; } }); });
关键注意事项
- 确保你的
article-cardsnippet中,每个文章卡片都有统一的article-cardclass,这样JS才能正确提取新内容。 - 检查博客模板顶部是否有分页声明:如果没有,需要在section最开头添加
{% paginate blog.articles by section.settings.articles_per_page %}(articles_per_page对应后台设置的每页显示数量,也可以直接写固定数字比如10)。 - 可根据主题样式调整
load-more-btn的外观,比如添加主题自带的按钮类。
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

