Javascript - DOM 重绘方法是否同步? [英] Javascript - Are DOM redraw methods synchronous?

查看:25
本文介绍了Javascript - DOM 重绘方法是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的问题中,DOM 重绘方法是那些修改 DOM 并导致浏览器重绘页面的方法.例如:

In my question, DOM redraw methods are those that modifies the DOM and cause browser to redraw the page. For example:

const newChildNode = /*...*/;

document.body.appendChild(newChildNode);

const newHeight = document.body.scrollHeight;

这段代码在正常情况下工作正常,但我不太确定它在高压条件下的表现如何,比如有很多重绘页面的请求.我可以假设当 document.body.scrollHeight 被执行时,newChildNode 已经在屏幕上可见了吗?

This code works fine under normal circumstances, but I am not so sure how it behaves under high pressure conditions, like when there are so many request to redraw the page. Can I assume that when document.body.scrollHeight is executed, newChildNode is already visible on screen?

推荐答案

我们可以将这个 重绘" 过程分为 3 个部分,DOM 更新Reflow, 重新绘制.

We can divide this "redraw" process in 3 parts, DOM update, Reflow, Repaint.

所有这些操作都不遵循相同的规则:

All these operations do not follow the same rules:

DOM 更新:始终同步.DOM只是另外一个js对象,它的操作方法都是同步的.

DOM update: Always synchronous. The DOM is just an other js object, and its manipulations methods are all synchronous.

回流:这就是你偶然发现的奇怪的野兽.这是页面上元素的所有框位置的重新计算.
通常,浏览器会等到您完成所有 DOM 修改,即 js 流结束,然后再触发它.
但是一些 DOM 方法会同步强制执行此操作.例如,所有 HTMLElement.offsetXXX 和类似的属性,或 Element.getBoundingClientRect,或访问 in-doc 的 Node.innerText 或访问某些属性getComputedStyle 返回的对象(可能还有其他对象)将触发 同步 回流,以便获得更新的值.所以当你使用这些方法/属性时要小心.

Reflow: That's the strange beast you stumbled upon. This is the recalculation of all box positions of the elements on the page.
Generally, browsers will wait until you finished all DOM modifications, and thus, the end of the js stream, before triggering it.
But some DOM methods will force this operation, synchronously. e.g, all the HTMLElement.offsetXXX and alike properties, or Element.getBoundingClientRect, or accessing in-doc's Node.innerText or accessing some properties of getComputedStyle returned object (, and probably others) will trigger a synchronous reflow, in order to have the updated values. So beware when you use these methods/properties.

重绘:当实际传递到渲染引擎时.规范中没有说明何时应该发生这种情况.大多数浏览器会等待下一次屏幕刷新,但并不是说它会一直这样.例如众所周知,当您使用 alert() 阻止脚本执行时,Chrome 不会触发它,而 Firefox 会.

Repaint: When things are actually passed to the rendering engines. Nothing in the specs says when this should happen. Most browsers will wait the next screen refresh, but it's not said it will always behave like that. e.g. Chrome is known for not triggering it when you blocked the scripts execution with alert(), while Firefox will.

这篇关于Javascript - DOM 重绘方法是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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