前端无限滚动与 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`为图片与复杂项使用占位与骨架屏可扩展与虚拟列表结合减少节点数,避免大列表内存压力总结通过观测器驱动的懒加载与批处理,可显著提升滚动性能与用户体验。

发表评论 取消回复