后端懒加载示例(以分页加载数据为例)
场景描述
假设有一个博客系统,每页显示10篇文章,用户滚动到底部时加载下一页的文章。
前端请求代码(使用Fetch API)
let page = 1;
const limit = 10;
let loading = false;
window.addEventListener("scroll", function() {
if (loading) return;
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
loading = true;
loadMoreArticles(page, limit);
}
});
function loadMoreArticles(page, limit) {
fetch(`/api/articles?page=${page}&limit=${limit}`)
.then(response => response.json())
.then(data => {
data.articles.forEach(article => {
// 将文章数据渲染到页面上
const articleElement = document.createElement("div");
articleElement.innerHTML = `<h2>${article.title}</h2><p>${article.content}</p>`;
document.body.appendChild(articleElement);
});
if (data.hasMore) {
page++;
} else {
window.removeEventListener("scroll", arguments.callee); // 移除滚动事件监听器(或使用其他方式避免重复加载)
}
loading = false;
})
.catch(error => {
console.error("Error loading articles:", error);
loading = false;
});
}
后端代码(Node.js + Express 示例)
const express = require("express");
const app = express();
// 模拟数据库中的文章数据
const articles = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
title: `Article ${i + 1}`,
content: `This is the content of article ${i + 1}.`
}));
app.get("/api/articles", (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const resultArticles = articles.slice(startIndex, endIndex);
const hasMore = endIndex < articles.length;
res.json({
articles: resultArticles,
hasMore: hasMore
});
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
解释:
前端部分:
监听
scroll
事件,当用户滚动到底部时,发送请求加载下一页的文章。使用
fetch
API请求后端API,获取文章数据并渲染到页面上。使用
loading
变量避免重复请求。后端部分:
接收前端请求,根据
page
和limit
参数返回相应的文章数据。判断是否还有更多文章,返回
hasMore
字段。
三、懒加载的优势
提高性能:减少初始加载时间,降低服务器压力。
节省带宽:只加载用户当前需要的数据或资源。
提升用户体验:加快页面响应速度,避免卡顿。
四、注意事项
SEO影响:对于需要SEO的内容,确保懒加载的内容能被搜索引擎抓取(如使用
noscript
标签或SSR)。兼容性:确保懒加载技术在目标浏览器上兼容(如使用
IntersectionObserver
API或polyfill)。错误处理:处理加载失败的情况,提供备用方案或重试机制。