In modern web design, Infinite Scrolling has become a popular content loading method that significantly enhances user experience, allowing visitors to maintain immersion while continuously browsing content. For users who build websites using AnQiCMS,archive/listThe interface is a powerful tool to implement this function. By skillfully using this interface, we can make the website's articles, products, or other document content automatically load more as the user scrolls the page, bringing a silky smooth browsing experience.

Get to knowarchive/listCore capability of the interface

archive/listThe interface is the core API provided by AnQi CMS for retrieving the document list.It can not only fetch content by page but also support various filtering and sorting conditions.When implementing infinite scrolling, we mainly use the following key parameters:

  • type=page: This parameter is the basis for implementing pagination loading. When set topageAt this time, the interface will return paginated data and include the total number of documents (total), this is crucial for determining if there is more content to load.
  • page: Used to specify which page of the request is currently being requested.
  • limit: Define the number of documents returned per page (or per request).
  • moduleId: If your website has multiple models (such as articles, products), you canmoduleIdSpecify to retrieve documents for a specific model.
  • categoryId: Allow you to filter documents by category, you can pass one or more category IDs.
  • order: Control the sorting method of documents, such as reverse chronological order by publication time (created_time desc) or by views (views desc).
  • Custom Filter Parameter: Flexible use of the customized fields configured in the AnQi CMS backend, which can be used as a filter to further accurately load content.

By reasonably combining these parameters, we can build a content list that meets various needs.

How to implement infinite scrolling on the front end?

Implementing infinite scrolling usually requires the cooperation of front-end JavaScript, and the following is the logical process and key steps to achieve this function.

Step 1: Load page data for the first time.

When a user first visits the page, we need to load the content of the first page of the document. This is usually done at page initialization by callingarchive/listthe interface. For example, we can setpage=1andlimit=10Retrieve 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 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.

Second step: listen to the scroll event to load more

The core of infinite scrolling lies in the logic that automatically triggers loading more content when the user scrolls to the bottom of the page.This requires us to listen for the page scroll event and determine if the user is nearing 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 frequentlyloadDocumentsA function, usually used in conjunction with debounce technology. This means that within a certain period of time, the action will only be executed after the scrolling stops or the frequency of scroll events is below a certain threshold.checkScrollForLoad.

Step 3: User-friendly Experience and Performance Optimization

  • Loading Indicator: AtisLoadingWithtrueDuring this time, you can display a 'Loading...' animation or text at the bottom of the page to let the user know that the content is loading.
  • “No more content” prompt: WhenhasMorechanges tofalseA “No more content” prompt is displayed to inform the user that they have viewed all the documents.
  • Error Handling: WhenloadDocumentsWhen a network error or other problem occurs, provide feedback to the user in a timely manner and offer a retry option.
  • Clean up event listeners: If the page no longer needs infinite scrolling (for example, when 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 capabilities. If your infinite scrolling list needs to support category filtering, keyword search, or sorting by popularity, you just need to call it every timeloadDocumentsWhen a function is called, the request parameters can be dynamically adjusted according to the user's choice.

For example, if the user selects the 'Technical Articles' category, then you canloadDocumentsadd to the request URL.categoryId=XIf the user enters a search keyword, it will be addedq=关键词. Each time the filter or sorting conditions are changed, it needs to be resetcurrentPage = 1and clear the current loaded document list, then call it againloadDocuments.

Summary

Byarchive/listThe integration of the interface with front-end JavaScript makes it not difficult to implement the infinite scrolling function of the Anqi CMS website.The key is to understand the role of interface parameters, as well as how to effectively manage pagination state, listen to scroll events, and provide good user feedback on the front end.This content loading method not only improves user experience, but also makes the presentation of website content more modern and dynamic.


Frequently Asked Questions (FAQ)

How to implement category filtering or keyword search in infinite scrolling?

When the user performs a category filter or enters a keyword search, you need to reset the state of the infinite scrolling component. Specifically, you should setcurrentPagethe variable to1Clear the current list of loaded documents, then call again based on the user's selected filter conditions (for examplecategoryIdorqparameters)loadDocumentsA function. This way, the interface will return the first page of data that meets the new conditions, and then the user can continue to scroll and load more content that meets the conditions.

2. Ifarchive/listThe API request failed, how should I handle it?

Good error handling is an important aspect of improving user experience. When the API request fails, you can usetry...catchError block caught. On the front end, you can display a friendly error message, such as 'Content load failed, please try again later', and provide a 'Retry' button for the user to manually attempt to reload.At the same time, willisLoadingSet the status tofalseEnsure the user can try to trigger loading again.

3. Does infinite scrolling affect the SEO of the website?

Infinite scrolling performs well in terms of user experience, but traditional search engine crawlers may not be able to effectively capture content loaded dynamically through JavaScript. To accommodate SEO, you can consider the following strategies:

  • Page rollback: Provides traditional pagination links as a backup, even on infinite scrolling pages, the bottom retains visible pagination navigation for use by crawlers.
  • Server-Side Rendering (SSR) Or PrerenderingIf your frontend framework supports it, you can pre-render some content on the server, or use a tool to pre-render your page into static HTML, so that search engine crawlers can directly capture the complete content.
  • Userel="next"andrel="prev"Tag: Add these tags in pagination links to help search engines understand the relationship between pages.

Although Anqi CMS'sarchive/listThe interface provides convenience for dynamic loading of the front-end, but additional attention is required during front-end development for SEO considerations.