In modern website design, Infinite Scrolling has become a popular content loading method, which can significantly enhance user experience, allowing visitors to maintain immersion while browsing content continuously. For users who build websites using AnQiCMS, archive/listThe interface is a powerful tool to implement this function.By cleverly utilizing this interface, we can enable the website's articles, products, or other document content to automatically load more as the user scrolls through the page, providing a silky smooth browsing experience.
Knowarchive/listThe core capability of the interface
archive/listThe interface is the core API provided by AnQi CMS for retrieving document lists.It not only can fetch content by page, but also supports multiple filtering and sorting conditions.
type=page: This parameter is the basis for implementing pagination loading. When set topage, the interface will return paginated data and include the total number of documents (totalThis is crucial for determining whether there is more content to load.pageIt is used to specify which page of content the current request is for.limit: Defines the number of documents returned per page (or per request).moduleId: If your website has multiple models (such as articles, products), you canmoduleId: Specify to retrieve documents for a specific model.categoryId[en] Allows you to filter documents by category, you can pass one or more category IDs.order[en] Controls the sorting method of the documents, such as sorting by publication time in reverse (created_time desc[en] or by views (views desc).- Custom filter parameters: Flexibly use the custom fields configured in the AnQi CMS backend, which can be used as filtering conditions to further accurately load content.
By reasonably combining these parameters, we can build content lists that meet various needs.
How to implement infinite scrolling on the front end?
Achieving infinite scrolling usually requires the cooperation of front-end JavaScript, and the following is the logical process and key steps to implement this feature.
Step 1: Load page data for the first time
When the user first visits the page, we need to first load the content of the first page. This is usually done at page initialization by callingarchive/listthe interface. For example, we can setpage=1andlimit=10Get the first 10 articles. After obtaining the data, display them in the corresponding area of the page.
// 假设这是您的AnQiCMS域名地址
const BASE_URL = 'https://yourdomain.com/api';
let currentPage = 1; // 追踪当前页码
const pageSize = 10; // 每页加载的数量
let isLoading = false; // 防止重复加载
let hasMore = true; // 标识是否还有更多内容
async function loadDocuments() {
if (isLoading || !hasMore) return; // 如果正在加载或没有更多内容,则退出
isLoading = true;
try {
const response = await fetch(`${BASE_URL}/archive/list?type=page&page=${currentPage}&limit=${pageSize}&moduleId=1&order=created_time desc`);
const result = await response.json();
if (result.code === 0 && result.data && result.data.length > 0) {
// 将获取到的文档渲染到页面
renderDocuments(result.data);
currentPage++; // 准备加载下一页
// 判断是否还有更多内容,如果当前页加载的数据量小于pageSize,说明是最后一页
if (result.data.length < pageSize || (result.total && (currentPage -1) * pageSize >= result.total)) {
hasMore = false;
displayNoMoreContent(); // 显示“没有更多内容”提示
}
} else {
hasMore = false; // 没有数据或发生错误,停止加载
displayNoMoreContent();
}
} catch (error) {
console.error('加载文档失败:', error);
// 可以显示错误提示
} finally {
isLoading = false;
}
}
// 首次加载
loadDocuments();
renderDocumentsThe function requires you to write it based on the specific structure of the page, its role is to render the document data obtained from the interface into HTML and add it to the page.
Step Two: Listen for scroll events to load more
The core of infinite scrolling lies in the logic of automatically loading more content when the user scrolls to the bottom of the page.This requires us to listen to the page's scroll event and determine if the user is approaching the bottom of the page.
function checkScrollForLoad() {
// 获取页面滚动的高度、可见区域高度和整个页面的高度
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 当滚动条距离底部只剩下一定距离(例如200px)时,触发加载
if (scrollTop + clientHeight >= scrollHeight - 200) {
loadDocuments();
}
}
// 添加滚动事件监听器,可以考虑使用防抖(debounce)优化性能
window.addEventListener('scroll', checkScrollForLoad);
To avoid triggering repeatedly when the user scrolls frequentlyloadDocumentsFunctions, often used in conjunction with debounce (debounce) technology. This means that the function will only be executed after a certain period of time, or when the frequency of scroll events is below a certain threshold.checkScrollForLoad.
Third step: Friendly user experience and performance optimization
- Loading indicatorOn:
isLoadingresponse fortrueDuring this time, you can display an 'Loading...' animation or text at the bottom of the page to let the user know that the content is loading. - “No more content” promptWhen
hasMoreChanges tofalseA “No more content” prompt is displayed, informing the user that they have viewed all the documents. - Error handlingWhen
loadDocumentsWhen a network error or other issue occurs, provide timely feedback to the user and offer a retry option. - Clean up event listeners: If the infinite scrolling is no longer needed in certain cases (such as, the user switches to another page), remember to remove the scroll event listener to prevent memory leaks.
Combine filtering and sorting
archive/listThe strength of the interface lies in its flexible filtering and sorting functions. If your infinite scrolling list needs to support category filtering, keyword search, or sorting by popularity, you just need to call it each timeloadDocumentsFunctions can dynamically adjust request parameters based on the user's selection.
For example, if the user selects the 'Technical Articles' category, then you canloadDocumentsadd it to the request URL.categoryId=XIf the user enters a search keyword, addq=关键词. Each time the filter or sort condition is changed, it needs to be resetcurrentPage = 1, and clear the currently loaded document list, then call it againloadDocuments.
Summary
Passarchive/listCombining interface with front-end JavaScript to implement the infinite scrolling function of a safe CMS website is not a difficult matter.The key lies in understanding the role of interface parameters, as well as how to effectively manage pagination state on the frontend, listen to scroll events, and provide good user feedback.This content loading method not only enhances the user experience, but also makes the presentation of website content more modern and dynamic.
Common Questions and Answers (FAQ)
How to implement category filtering or keyword search in infinite scrolling?
When the user performs category filtering or enters a keyword search, you need to reset the state of the infinite scrolling component. Specifically, setcurrentPagethe variable to1Clear the currently loaded document list and then call according to the user's selected filter conditions (for example,categoryIdorqthe parameters) againloadDocumentsFunction. In this way, the interface will return the first page of data that meets the new conditions, and then the user can continue to scroll to load more content that meets the conditions.
2. Ifarchive/listThe interface request failed, how should I handle it?
Good error handling is an important part of enhancing user experience. When the interface request fails, you cantry...catchBlock capture error.In the frontend, you can display a friendly error message, such as 'Content loading failed, please try again later', and provide a 'Retry' button for the user to manually attempt to reload.isLoadingSet the status tofalseEnsure that the user can attempt to trigger loading again.
3. Does infinite scrolling have an impact on the website's SEO?
Infinite scrolling performs well in terms of user experience, but traditional search engine crawlers may not be able to crawl content loaded dynamically through JavaScript well. To兼顾SEO, you can consider the following strategies:
- Page Navigation Back: Provides traditional pagination links as a backup, even on infinite scrolling pages, the bottom retains visible pagination navigation for crawlers.
- Server-Side Rendering (SSR) or PrerenderingIf your front-end framework supports it, you can pre-render some content on the server side, or use a tool to pre-render your page into static HTML, so that search engine crawlers can directly capture the complete content.
- Use
rel="next"andrel="prev"tagsIn pagination links, add these tags to help search engines understand the relationship between pages.
Although the Anqi CMS isarchive/listThe interface provides convenience for dynamic loading on the front end, but additional attention is required for SEO considerations during front-end development.