search
HomeWeb Front-endHTML TutorialJavaScript and REST API to implement infinite scroll pagination

Infinite scroll pagination is inspired by sites like Facebook and Twitter. This is just pagination, when the user scrolls to the bottom of the page, more content is loaded. This improves the user experience on your website by ensuring there is always more content on the page for users to read.

Perform infinite scroll paging correctly

When implementing infinite scroll pagination, there are some very important points to remember.

Important links should not be at the bottom of the page. This is because a new set of entries is loaded every time the user tries to scroll down to find them. All important links should be pinned to the sidebar or remain permanently at the top.

2.Plan ahead

It is important to plan where you will include pagination and how you will handle it. A common way to do pagination is to list page numbers at the bottom of the page. However, when you use the infinite scroll method, the page numbers will no longer appear at the end of the article list because they are no longer needed. This pagination can be used with all themes as long as you don't include a lot of information in the footer section, as it may not have the desired effect.

In this tutorial, we will learn how to implement infinite scroll functionality in JavaScript.

This page will display a list of interesting facts about cats, which information will come from the API. The API returns 10 interesting facts by default. When you scroll to the bottom of the page, the app will display an indicator to indicate the loading status of the app. At the same time, the application will call the API to load the next set of interesting facts.

We will use this URL to load interesting facts. The API accepts the query string page, which tells the API which page to load.

https://catfact.ninja/facts?page=${page}&limit=${limit}

JavaScript和REST API实现无限滚动分页

Now, let's start using the application.

1. Create project structure

First, create a folder with the following structure.

root
-- index.html
-- style.css
-- app.js

2. Build HTML file

Our HTML file will contain several sections:

  1. A container in which the entire scrollable list of interesting facts will be rendered
  2. quotes section containing each interesting fact
  3. loader, will be visible when loading interesting facts. loader Invisible by default.
<div class="container">
  <h1 id="Fun-Facts-about-Cats">Fun Facts about Cats</h1>

  <div class="facts">
  </div>

  <div class="loader">
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>

3.Build script

Next, we need to create a script that will connect the divs and load the fun facts. To do this we will use querySelector().

const factsEl = document.querySelector('.facts');
const loader = document.querySelector('.loader');

We also need some control variables to define which set of items will be displayed on the screen. The control variables in this code are:

  • currentPage: The current page is initialized to 1. When scrolling to the bottom of the page, the current page will be incremented by 1 and an API request will be made to obtain the content page of the next page. When the page is scrolled to the top, the current page will be decremented by 1.
  • total: This variable stores the total number of quotes returned by the Fun Facts API.

4. Build getFacts Function

getFactsThe function is to call the API and return interesting facts. getFacts The function accepts a single parameter: page. It uses the Fetch API mentioned above to get data for infinite scrolling.

Fetch always returns promise, so we will use the await-async syntax to receive and handle the response. To get the json data we will use the json() function. getFacts The function returns a promise that will parse and return JSON.

const getfacts = async (page, limit) => {
    const API_URL = `https://catfact.ninja/facts?page=${page}&limit=${limit}`;
    const response = await fetch(API_URL);
    // handle 404
    if (!response.ok) {
        throw new Error(`An error occurred: ${response.status}`);
    }
    return await response.json();
}

5. Build showFacts Functions

Now that we have received the interesting facts, where can we display them? That's why we need to have a showFacts function. The showFacts function works by iterating over an array of facts. It then creates an HTML representation of the fact object using the template Literal syntax.

const showfacts = (facts) => {
    facts.forEach(fact => {
        const factEl = document.createElement('blockfact');
        factEl.classList.add('fact');
        factEl.innerHTML = `
            ${fact.fact}
        `;
        factsEl.appendChild(factEl);
    });
};

An example of a generated blockFact element is:

<blockfact class="fact">
      Unlike dogs, cats do not have a sweet tooth. Scientists believe this is due to a mutation in a key taste receptor.
</blockfact>

We use the appendChild function to add the <blockfact></blockfact> element to the container.

6.显示和隐藏加载指示器

当用户到达页面末尾时,必须显示加载指示器。为此,我们将引入两个函数:一个用于加载,另一个用于隐藏加载器。我们将使用 opacity: 1 显示加载程序,并使用 opacity: 0 隐藏加载程序。添加和删​​除 opacity 将分别显示/隐藏加载程序。

const hideLoader = () => {
    loader.classList.remove('show');
};

const showLoader = () => {
    loader.classList.add('show');
};

7.查看更多有趣的事实

为了提高性能,我们将引入一个函数来检查 API 是否有更多事实。如果还有更多项目要获取,则 hasMoreFacts() 函数将返回 true。如果没有更多项目可供获取,API 调用将停止。

const hasMorefacts = (page, limit, total) => {
    const startIndex = (page - 1) * limit + 1;
    return total === 0 || startIndex < total;
};

8. 编写 loadFacts 函数代码

loadFacts 函数负责执行这些重要操作:

  • 显示或隐藏加载指示器
  • 调用 getFacts 函数获取更多事实
  • 展示事实
const loadfacts = async (page, limit) => {
    // show the loader
    showLoader();
    try {
        // if having more facts to fetch
        if (hasMorefacts(page, limit, total)) {
            // call the API to get facts
            const response = await getfacts(page, limit);
            // show facts
            showfacts(response.data);
            // update the total
            total = response.total;
        }
    } catch (error) {
        console.log(error.message);
    } finally {
        hideLoader();
    }
};

从某种意义上说,这种实现的一个缺点是它的运行速度。大多数时候您不会看到加载指示器,因为 API 可以很快返回。如果您想在每次滚动时查看加载指示器,可以使用 setTimeout 函数。调整 setTimeout 函数的 delay 将决定加载指示器显示的时间长度。

9. 处理滚动事件

当用户滚动到页面底部时,需要一个scroll事件处理程序来调用loadFacts函数。如果满足以下条件,该函数将被调用:

  • 滚动条已到达页面底部
  • 还有更多事实需要加载

为了实现滚动事件,我们将使用三个窗口属性:

  • window.scrollHeight 给出整个文档的高度。
  • window.scrollY 给出了用户滚动文档的距离。
  • window.innerHeight 给出可见窗口的高度。

下图更好地概述了上述属性。另外,您将能够理解,如果 innerHeightscrollY 之和等于或大于 scrollHeight,则到达文档末尾,此时必须加载更多有趣的事实。

JavaScript和REST API实现无限滚动分页

window.addEventListener('scroll', () => {
    const {
        scrollTop,
        scrollHeight,
        clientHeight
    } = document.documentElement;

    if (scrollTop + clientHeight >= scrollHeight - 5 &&
        hasMoreFacts(currentPage, limit, total)) {
        currentPage++;
        loadFacts(currentPage, limit);
    }
}, {
    passive: true
});

10.初始化页面

无限滚动的最后一步是初始化页面。调用 loadFacts 来加载第一组有趣的事实非常重要。

loadfacts(currentPage, limit);

现场演示

结论

现在,我们在 JavaScript 中实现了一个简单的无限滚动,每当用户滚动时,它将获取并呈现有关猫的有趣事实。这只是无限滚动最常用的方法之一。

The above is the detailed content of JavaScript and REST API to implement infinite scroll pagination. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment