JavaScript and REST API to implement infinite scroll pagination
Sep 11, 2023 pm 10:41 PMInfinite 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.
1.Don’t put important links at the bottom
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}
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:
- A
container
in which the entire scrollable list of interesting facts will be rendered quotes
section containing each interesting factloader
, will be visible when loading interesting facts.loader
Invisible by default.
<div class="container"> <h1>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
getFacts
The 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>
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
函數負責執(zhí)行這些重要操作:
- 顯示或隱藏加載指示器
- 調用
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
給出可見窗口的高度。
下圖更好地概述了上述屬性。另外,您將能夠理解,如果 innerHeight
和 scrollY
之和等于或大于 scrollHeight
,則到達文檔末尾,此時必須加載更多有趣的事實。
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To use HTML button elements to achieve clickable buttons, you must first master its basic usage and common precautions. 1. Create buttons with tags and define behaviors through type attributes (such as button, submit, reset), which is submitted by default; 2. Add interactive functions through JavaScript, which can be written inline or bind event listeners through ID to improve maintenance; 3. Use CSS to customize styles, including background color, border, rounded corners and hover/active status effects to enhance user experience; 4. Pay attention to common problems: make sure that the disabled attribute is not enabled, JS events are correctly bound, layout occlusion, and use the help of developer tools to troubleshoot exceptions. Master this

Metadata in HTMLhead is crucial for SEO, social sharing, and browser behavior. 1. Set the page title and description, use and keep it concise and unique; 2. Add OpenGraph and Twitter card information to optimize social sharing effects, pay attention to the image size and use debugging tools to test; 3. Define the character set and viewport settings to ensure multi-language support is adapted to the mobile terminal; 4. Optional tags such as author copyright, robots control and canonical prevent duplicate content should also be configured reasonably.

TolearnHTMLin2025,chooseatutorialthatbalanceshands-onpracticewithmodernstandardsandintegratesCSSandJavaScriptbasics.1.Prioritizehands-onlearningwithstep-by-stepprojectslikebuildingapersonalprofileorbloglayout.2.EnsureitcoversmodernHTMLelementssuchas,

How to make HTML mail templates with good compatibility? First, you need to build a structure with tables to avoid using div flex or grid layout; secondly, all styles must be inlined and cannot rely on external CSS; then the picture should be added with alt description and use a public URL, and the buttons should be simulated with a table or td with background color; finally, you must test and adjust the details on multiple clients.

Using HTML sums allows for intuitive and semantic clarity to add caption text to images or media. 1. Used to wrap independent media content, such as pictures, videos or code blocks; 2. It is placed as its explanatory text, and can be located above or below the media; 3. They not only improve the clarity of the page structure, but also enhance accessibility and SEO effect; 4. When using it, you should pay attention to avoid abuse, and apply to content that needs to be emphasized and accompanied by description, rather than ordinary decorative pictures; 5. The alt attribute that cannot be ignored, which is different from figcaption; 6. The figcaption is flexible and can be placed at the top or bottom of the figure as needed. Using these two tags correctly helps to build semantic and easy to understand web content.

When there is no backend server, HTML form submission can still be processed through front-end technology or third-party services. Specific methods include: 1. Use JavaScript to intercept form submissions to achieve input verification and user feedback, but the data will not be persisted; 2. Use third-party serverless form services such as Formspree to collect data and provide email notification and redirection functions; 3. Use localStorage to store temporary client data, which is suitable for saving user preferences or managing single-page application status, but is not suitable for long-term storage of sensitive information.

class, id, style, data-, and title are the most commonly used global attributes in HTML. class is used to specify one or more class names to facilitate style setting and JavaScript operations; id provides unique identifiers for elements, suitable for anchor jumps and JavaScript control; style allows for inline styles to be added, suitable for temporary debugging but not recommended for large-scale use; data-properties are used to store custom data, which is convenient for front-end and back-end interaction; title is used to add mouseover prompts, but its style and behavior are limited by the browser. Reasonable selection of these attributes can improve development efficiency and user experience.

Native lazy loading is a built-in browser function that enables lazy loading of pictures by adding loading="lazy" attribute to the tag. 1. It does not require JavaScript or third-party libraries, and is used directly in HTML; 2. It is suitable for pictures that are not displayed on the first screen below the page, picture gallery scrolling add-ons and large picture resources; 3. It is not suitable for pictures with first screen or display:none; 4. When using it, a suitable placeholder should be set to avoid layout jitter; 5. It should optimize responsive image loading in combination with srcset and sizes attributes; 6. Compatibility issues need to be considered. Some old browsers do not support it. They can be used through feature detection and combined with JavaScript solutions.
