Skip to content
Advertisement

Why doesn’t window.getComputedStyle invoke recalculate styles and reflow?

Look at this example:

JavaScript

and look at another one:

JavaScript

Differences are minimal: in the first case I just invoke window.getComputedStyle(document.body) without getting property, and in the second case I doing it with width property. As a result in first one we don’t see recalculation styles and reflows but in the second one we see vesa versa situation. Why?

Advertisement

Answer

This is because getComputedStyle(element) actually returns a live object.

JavaScript
JavaScript
JavaScript

Getting this object doesn’t require that a full recalc is performed, only its getters will force it.

But browsers are nowadays even smarter than just that, they won’t even trigger a reflow for some properties outside of the CSSOM tree that affects the CSSStyleDeclaration object being inspected.

For instance in the following example we can see that getting the fontSize property from the CSSStyleDeclaration of an element that is inside our checker will force a reflow affecting our checker, while getting one form outside won’t, because unlike width, the fontSize property is only affected by ancestors and not by siblings.

JavaScript
JavaScript
JavaScript

The same checking for width would trigger in both cases, because width can be affected by siblings:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement