其他分享
首页 > 其他分享> > 为什么在重画后安排一些东西时建议将setTimeout嵌套在requestAnimationFrame中?

为什么在重画后安排一些东西时建议将setTimeout嵌套在requestAnimationFrame中?

作者:互联网

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,这是您可以做的最好的事情.

标签:repaint,requestanimationframe,settimeout,browser,javascript
来源: https://codeday.me/bug/20191110/2015111.html