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

查看:89
本文介绍了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更新重排重涂

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 ,或访问文档中的 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天全站免登陆