What Does will-change In CSS Do?
14 days ago
- #Animations
- #Performance
- #CSS
- The `will-change` CSS property is a performance optimization hint to browsers, indicating that certain properties of an element are about to change.
- Browsers may respond by promoting the element to its own GPU compositing layer, pre-allocating memory, or ignoring the hint if deemed unnecessary.
- The browser rendering process involves three steps: Layout (CPU), Paint (CPU and memory), and Compose (GPU).
- `will-change` helps skip Layout and Paint steps for compositor-friendly properties like `transform` and `opacity`, allowing GPU to handle animations smoothly.
- Without `will-change`, the browser promotes an element to its own layer only when the animation starts, potentially causing stutter in the first frames.
- `will-change` can pre-promote elements during idle time, ensuring smooth animations from the first frame.
- Effective use of `will-change` involves specifying exact properties (e.g., `transform`, `opacity`) rather than broad declarations like `all`.
- Properties like `transform`, `opacity`, `filter`, `clip-path`, and `mask` benefit most from `will-change`, while others like `top` or `background` offer little to no performance gain.
- `will-change` should be used sparingly and intentionally, as it is computationally expensive and can impact performance if overused.
- Modern browsers are already optimized for animations, but `will-change` can be crucial for complex animations requiring smoothness from the first frame.