Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is involved in Chrome's Recalculate Style Event?

TL;DR

What causes Recalculate Style in Chrome and what could be done to reduce the time for this step?

Background

In an application with many elements (variable, e.g. 10,000) I observe Recalculate Style taking a long time when adding a class on the parent element of those elements. There are selectors that will affect elements of each subtree when the container has this class.

In the developer tools I was able to trace the cause of the Recalculate Style event by clicking here (screenshot of a MCVE):

Chrome dev tools: how to trace back the event cause

From to the name I assume that this step involves calculating the effective (final) element style. I think this happens when

  1. a changed element style,
  2. a changed (pseudo-) class

    • of the element itself or
    • of a parent or sibling element that is related by a selector or
  3. a changed CSS selector (importing new CSS, generating <style>)

forces the browser to recalculate the CSS attributes of an element.

Attempt to prove my thesis

I created a MCVE with the same amount of elements as static HTML and toggling a class .change on a .container using a click handler on the document - dead simple code.

The MCVE performs much better than the actual application, the step Recalculate Style takes less time. This is probably due to the simpler tree and less styles.

Then I started adding more styles to all selectors and the average time increased with every bunch of new CSS attributes. Adding more elements to the 10,000 subtrees did not change the average time.

So, I'd say that the amount of CSS attributes, the count of selectors affected and the count of elements affected influences this time.

like image 964
try-catch-finally Avatar asked Nov 08 '22 22:11

try-catch-finally


1 Answers

Recalculate Style

  1. Get all the style rules
  2. Evaluate the selectors and match against the DOM
  3. Calculate the computed style for every element

Basically anytime you change a classname or other operations like that.

References

  • https://youtu.be/0xx_dkv9DEY?t=204
  • https://developers.google.com/web/fundamentals/performance/rendering/reduce-the-scope-and-complexity-of-style-calculations
like image 60
Tim Arney Avatar answered Nov 15 '22 08:11

Tim Arney