前端无限滚动与 IntersectionObserver 性能优化基本实现<ul id="list"></ul> <div id="sentinel"></div> <script> const list = document.getElementById('list'); async function loadMore() { const res = await fetch('/api/items?cursor=' + cursor); const data = await res.json(); data.items.forEach(it => { const li = document.createElement('li'); li.textContent = it.name; list.appendChild(li); }); cursor = data.nextCursor; } let cursor = ''; const io = new IntersectionObserver((entries) => { if (entries[0].isIntersecting) requestIdleCallback(loadMore); }, { rootMargin: '200px', threshold: 0 }); io.observe(document.getElementById('sentinel')); </script> 性能要点使用 `rootMargin` 预取,避免突兀卡顿采用批量 DOM 更新与 `requestIdleCallback`/`requestAnimationFrame`为图片与复杂项使用占位与骨架屏可扩展与虚拟列表结合减少节点数,避免大列表内存压力总结通过观测器驱动的懒加载与批处理,可显著提升滚动性能与用户体验。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.974239s