用一个固定尺寸的滚动容器观察 IntersectionObserver 的百分比边距,再用像素固定预加载距离。
为什么 rootMargin 的 50% 会让预加载距离随浏览器变化?
时间:2026-11-30
浏览:313
文章目录
长列表预加载通常依赖末尾的哨兵元素提前进入 IntersectionObserver 的观察范围。将底部边距设为 50%,看似能提前半个容器高度触发,实际的触发距离取决于浏览器拿哪条边来算。
先弄清 50% 是谁的一半
假设容器宽 320px、高 480px。规范要求用扩展前的根矩形宽度计算 rootMargin 的百分比,底部的 50% 就是 160px。当前 Chromium 源码对上下两侧用的是高度,同样的设置会算出 240px。

把这段代码贴进空白页的控制台。目标元素从容器顶部下方 680px 处开始,离可见区域的底边正好 200px。代码只向下扩展观察范围,因此首次回调里的 rootBounds.height 就是容器高度加上底部边距。
const root = document.createElement('div')
Object.assign(root.style, {
width: '320px',
height: '480px',
overflow: 'hidden',
padding: '0',
border: '0'
})
const spacer = document.createElement('div')
spacer.style.height = '680px'
const target = document.createElement('div')
target.style.height = '16px'
root.append(spacer, target)
document.body.append(root)
function logEntry(label, { rootBounds, isIntersecting }) {
console.log(
`${label} rootBounds.height=${rootBounds.height} isIntersecting=${isIntersecting}`
)
}
const percentObserver = new IntersectionObserver(([entry], observer) => {
logEntry('50%', entry)
observer.disconnect()
}, { root, rootMargin: '0px 0px 50% 0px' })
percentObserver.observe(target)
看首次回调里的两个值
按规范计算,观察范围到 640px 为止,离目标还有 40px,isIntersecting 是 false。按当前 Chromium 源码的算法,观察范围到 720px,已经覆盖目标,结果是 true。图中前两行是两种算法各自的预期输出,第三行对应下面的像素写法。

用像素指定预加载距离
想提前半个容器高度触发,就用 root.clientHeight / 2 算出底部边距,再带上像素单位传进去。这个例子会传入 240px,观察范围都会延伸到 720px。rootMargin 在创建时确定,所以用 ResizeObserver 监听容器大小变化,算出的边距变了就重建观察器。
function watchAtHalfHeight(root, target, onApproach) {
let observer
let previousBottom
function update() {
const bottom = root.clientHeight / 2
if (bottom === previousBottom) return
previousBottom = bottom
observer?.disconnect()
observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) onApproach(entry)
}, {
root,
rootMargin: `0px 0px ${bottom}px 0px`
})
observer.observe(target)
}
const sizes = new ResizeObserver(update)
sizes.observe(root)
update()
return () => {
sizes.disconnect()
observer.disconnect()
}
}
const stop = watchAtHalfHeight(root, target, entry => logEntry('px', entry))
// 页面离开或组件卸载时调用 stop()

本例容器无内边距或滚动条,clientHeight 即为计算基准。处理列表请求时,需结合加载状态或分页游标去重。新建观察器会产生初始记录,若目标已在范围内,即使未滚动也可能再次触发预加载回调。
排查页面时,可以同时打印容器高度、展开后的 rootBounds.height 和 isIntersecting。先确认观察边界有没有碰到哨兵,再检查分页请求有没有接住这次回调。
实用工具推荐
绿化、压缩、噪点和虚拟水印,自由调节做旧程度。
选择画质和输出格式,预览压缩前后的大小。