在 mozilla docs on performance best practices for front-end engineers建议结合setTimeout
与 requestAnimationFrame
在重绘后立即运行:
requestAnimationFrame(() => {
setTimeout(() => {
// This code will be run ASAP after Style and Layout information have
// been calculated and the paint has occurred. Unless something else
// has dirtied the DOM very early, querying for style and layout information
// here should be cheap.
}, 0);
});
为什么这是推荐的解决方案?究竟是什么让这成为在重绘后立即安排某事的最佳方式?
请您参考如下方法:
Why is this the recommended solution? What exactly makes this the optimal way to schedule something right after a repaint?
在重绘后立即运行代码可以最大限度地提高 DOM 已被完全计算出来的机会,从而最大限度地减少查询 dom 导致代价高昂的重排的机会。如果您仍然不查询 dom,那么这不是您需要担心的事情。
requestAnimationFrame 将安排代码在重绘之前立即运行,这接近您想要的位置但不完全。所以然后做一个
setTimeout
0 (或
setImmediate
在支持它的浏览器上)将在之后尽快执行代码。这并不能保证您的代码是重绘后首先运行的代码,但鉴于您可以使用的 api,这是您能做的最好的事情。