How to use the `archive/list` interface to dynamically load more documents on the front end (infinite scrolling)?

Calendar Eye 133

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.

Related articles

What is the help of `archive/list` interface returned `canonical_url` and `fixed_link` fields to SEO optimization?

In the ocean of website content, how can our high-quality content stand out and be discovered by more potential users, which is a topic that every content operator continuously explores.Search engine optimization (SEO) is one of the key strategies to achieve this goal.In SEO practice, the URL plays an extremely important role.

2025-11-09

What will `data` and `total` return if no documents meeting the criteria are found in the AnQiCMS document list?

When building a website or application with AnQiCMS, we often need to use its provided API interface to retrieve various content, such as document lists.What data structure will the API return when our query conditions do not match any content?Especially the `data` and `total` fields, which are crucial for our proper data handling.Today, let's delve into how AnQi CMS responds when it does not find a document that meets the criteria in the document list.

2025-11-09

How to implement a 'Hot Articles' or 'Most Viewed' list, achieved through the `order` parameter?

In website operation, we all hope to display the most popular and highly read articles to visitors, such as common lists like "Hot Articles" or "Most Viewed".This not only effectively guides users to discover more exciting content and improve the user experience of the website, but it is also an indispensable part of content operation.In AnQi CMS, implementing such a feature is simpler than you imagine, the secret is hidden in the `archive/list` interface's `order` parameter.

2025-11-09

What is the default behavior and return content of the `archive/list` interface when no parameters are passed?

## In-depth Analysis of AnQiCMS `archive/list` Interface: Default Behavior and Return Content when No Parameters Are Provided When developing or managing websites with AnQiCMS, we often need to obtain various data through API interfaces.The `archive/list` interface is one of the core interfaces for obtaining the document list of the website.Understanding its default behavior and return content when no parameters are passed is crucial for efficient data acquisition and initial debugging.

2025-11-09

Does the AnQiCMS document list interface support complex queries on the returned data's `extra` field?

In Anqi CMS, the flexibility of document content management is a highly关注的 feature, especially its support for custom fields (manifested in the `extra` field returned by the interface), providing great convenience for website operators.When we need to filter and query a large number of documents based on these custom properties, we naturally think of a key question: Does the Anqi CMS document list interface (`/api/archive/list`) support more complex queries on the `extra` field in the returned data?

2025-11-09

How to use the results of `archive/list` to implement click to view article details in conjunction with `archiveDetail.md`?

When building a website, displaying an article list and allowing users to click to view the details of the articles is a basic and core function.AnQiCMS (AnQiCMS) provides a powerful and flexible API interface, allowing us to easily achieve this requirement.Next, we will discuss how to use the `archive/list` interface to get an article summary and then use the `archive/detail` interface to display the full article content when the user clicks.

2025-11-09

What error message will the `archive/list` interface return when the `moduleId` parameter is invalid?

When building a website with AnQiCMS, the `archive/list` interface is undoubtedly the core tool for obtaining the content list.Through this interface, we can flexibly filter and display various documents, meeting the dynamic content needs of the website front-end.Among them, the `moduleId` parameter plays a very crucial role, allowing us to specify the document under a specific content model (such as articles, products, news, etc.).

2025-11-09

GEO Generation Engine Optimization: A Survival Guide for Corporate Websites in the 2025 AI Search Era

GEO Generative Engine Optimization is a new skill that corporate websites must master in the AI search era of 2025.This article explains the core strategy of GEO and how to use Anqi CMS for AI search optimization to seize traffic opportunities.

2026-06-11