javascript - 什么时候在 DOM 环境中发生回流?

标签 javascript performance dom reflow

什么样的事件会触发带DOM的网页回流?

似乎有不同的观点。根据http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/ , 它发生了

  • 当您添加或删除 DOM 节点时。
  • 当您动态应用样式时(例如 element.style.width="10px")。
  • 当您检索必须计算的测量值时,例如访问 offsetWidth、clientHeight 或任何计算出的 CSS 值(通过兼容 DOM 的浏览器中的 getComputedStyle() 或 IE 中的 currentStyle)。

然而,根据http://dev.opera.com/articles/view/efficient-javascript/?page=3 , 仅当已经有回流操作排队时才进行测量触发回流。

有没有人有更多的想法?

最佳答案

这两篇文章都是正确的。 可以安全地假设,无论何时您正在做一些可能合理地要求计算 DOM 中元素的尺寸的事情,您都会触发回流。

另外,据我所知,这两篇文章说的是同一件事。

第一篇文章说回流发生在:

When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made.

第二条指出:

As stated earlier, the browser may cache several changes for you, and reflow only once when those changes have all been made. However, note that taking measurements of the element will force it to reflow, so that the measurements will be correct. The changes may or may not not be visibly repainted, but the reflow itself still has to happen behind the scenes.

This effect is created when measurements are taken using properties like offsetWidth, or using methods like getComputedStyle. Even if the numbers are not used, simply using either of these while the browser is still caching changes, will be enough to trigger the hidden reflow. If these measurements are taken repeatedly, you should consider taking them just once, and storing the result, which can then be used later.

我认为这与他们之前所说的意思相同。 Opera 会尽最大努力为您缓存值并避免回流,但您不应该依赖它这样做的能力。

无论出于何种意图和目的,只要相信他们所说的所有三种类型的交互都会导致回流。

干杯。

关于javascript - 什么时候在 DOM 环境中发生回流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/510213/

相关文章:

javascript - 使用 Moment.js 制作原生 ELM 模块

javascript - 附有 javascript magic 的复选框不会取消选中

arrays - 矩阵中的累积和

javascript - 将焦点设置到 iframe 内容

javascript - 防止点击 anchor 内 DOM 生成的元素时的 anchor 行为

javascript - 显示 JSON 数据的下载进度百分比

javascript - 如何在 jQuery 中解析日期字符串并检查它是否在过去

c++ - 为什么 glReadPixels 这么慢并且有其他选择吗?

java - Linux调优Java并发性能

javascript - 如何逐步向一个元素添加 2 个类