EJS滚动加载更多容器功能异常,求修复方案
修复滚动加载更多功能的问题
前端EJS/JS问题修复
1. 修正滚动触发逻辑(解决偶尔不调用路由的问题)
滚动判断条件不准确或未加请求锁是触发不稳定的核心原因,以下是修正后的逻辑:
// 全局加载锁,避免重复请求 window.isLoading = false; // 分页参数 let currentPage = 1; const itemsPerPage = 10; // 绑定滚动事件(确保DOM加载完成后执行) document.addEventListener('DOMContentLoaded', () => { window.addEventListener('scroll', handleScroll); }); function handleScroll() { if (window.isLoading) return; const scrollTop = window.pageYOffset || document.documentElement.scrollTop; const windowHeight = window.innerHeight; const documentHeight = document.documentElement.scrollHeight; // 距离底部200px时提前触发,提升体验 if (scrollTop + windowHeight >= documentHeight - 200) { window.isLoading = true; loadMoreItems(); } }
2. 修复加载与渲染逻辑(解决新项目无法渲染的问题)
EJS是服务端模板,客户端无法直接解析,需用JS动态生成DOM:
function loadMoreItems() { fetch(`/loadmore?page=${currentPage}&limit=${itemsPerPage}`) .then(res => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .then(data => { if (data.items.length === 0) { window.removeEventListener('scroll', handleScroll); alert('已加载全部内容'); return; } const container = document.getElementById('items-container'); data.items.forEach(item => { const itemEl = document.createElement('div'); itemEl.className = 'item-card'; // 根据你的项目结构拼接HTML itemEl.innerHTML = ` <h3>${item.title}</h3> <p>${item.description}</p> `; container.appendChild(itemEl); }); currentPage++; window.isLoading = false; }) .catch(err => { console.error('加载失败:', err); window.isLoading = false; }); }
后端Node.js路由修复
1. 正确处理分页参数
确保路由正确解析分页参数,返回格式规范的JSON数据:
// 示例项目数据 const sampleItems = [ { id: 1, title: "项目1", description: "描述内容1" }, { id: 2, title: "项目2", description: "描述内容2" }, // ... 更多测试数据 ]; app.get('/loadmore', (req, res) => { // 禁用缓存,避免返回旧数据 res.set('Cache-Control', 'no-cache, no-store, must-revalidate'); const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; const startIdx = (page - 1) * limit; const endIdx = startIdx + limit; const paginatedItems = sampleItems.slice(startIdx, endIdx); res.json({ items: paginatedItems, hasMore: endIdx < sampleItems.length }); });
关键坑点排查
- 请求锁必须加:滚动事件会连续触发,不加锁会导致重复请求,甚至接口阻塞
- DOM加载时机:滚动事件务必在
DOMContentLoaded后绑定,否则可能找不到容器元素 - 容器高度计算:如果用自定义滚动容器而非窗口,需替换为容器的
scrollTop、clientHeight、scrollHeight属性 - JSON格式合法性:后端返回的JSON不能有语法错误,否则前端解析失败
内容的提问来源于stack exchange,提问作者FattyDev1
相关产品推荐
相关产品推荐

