为什么读取 DOM 测量值会触发布局/回流? [英] Why does reading DOM measurements trigger a layout/reflow?

查看:43
本文介绍了为什么读取 DOM 测量值会触发布局/回流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常读到在阅读元素的样式后更改样式是一种不好的做法,因为它会触发不必要的回流.考虑来自此处的这段代码:

I often read that changing a style after reading the element's style is a bad practice as it triggers an unnecessary reflow. Consider this code from here:

错误代码:

elementA.className = "a-style";
var heightA = elementA.offsetHeight;  // layout is needed
elementB.className = "b-style";       // invalidates the layout
var heightB = elementB.offsetHeight;  // layout is needed again

好的代码:

elementA.className = "a-style";
elementB.className = "b-style";
var heightA = elementA.offsetHeight;   // layout is needed and calculated
var heightB = elementB.offsetHeight;   // layout is up-to-date (no work)

我很想知道为什么 elementA.offsetHeight 会导致布局?这里我们只是读取已经应用的更改,而不是真正应用更改(例如 elementA.className = "a-style" 的情况).

I am curious to know why elementA.offsetHeight will cause a layout? Here we are simply reading already applied changes, not really applying a change (like in case of elementA.className = "a-style").

推荐答案

这里我们只是读取已经应用的更改...

Here we are simply reading already applied changes...

不是真的.分配给 className 意味着浏览器必须重排,但这并不意味着当您完成分配时它已经重排.它可能会等待(在现代浏览器中,会等待)直到它的下一次绘制,这直到当前 JavaScript 代码完成(至少)之后才会发生.

Not really. Assigning to className means the browser has to reflow, but it doesn't mean it already has reflowed when you're done assigning. It may wait (in modern browsers, will wait) until its next paint, which won't happen until after the current JavaScript code completes (at least).

但是当您读取像 clientHeight 这样的计算属性时,浏览器必须暂停 JavaScript 代码并重排页面,以便返回准确的数字.所以你的好"代码是这样的:

But when you read a calculated property like clientHeight, the browser has to pause the JavaScript code and reflow the page so it can return an accurate number. So your "good" code does this:

elementA.className = "a-style";        // marks the layout stale
elementB.className = "b-style";        // marks the layout stale (no change)
var heightA = elementA.offsetHeight;   // triggers reflow
var heightB = elementB.offsetHeight;   // no need for reflow, the layout isn't stale

这篇关于为什么读取 DOM 测量值会触发布局/回流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆