I just heard about CSS’s will-change property, which I am particularly interested in because getting websites to run well on mobile is hard.
will-change is a CSS draft specification right now. Its purpose is to provide a hint to the browser that the provided properties can possibly change, allowing the browser to preemptively perform expensive operations before it happens, when the user is expecting a smooth result.
Why is this a problem?
Browsers try to be smart by performing optimizations so that your website loads faster and users have a better user experience. CSS is usually a pretty static thing. “This box is going to be red, it’s going to be this size and placed over here.” The majority of CSS properties do not change after the page has loaded. But to make websites interactive or ease the shock of a significant state-change, we employ animations. In order to animate elements, we must change their properties. The browser didn’t think these properties were going to ever change: if it did, perhaps it would have done something differently. Perhaps the browser even catches on that an element is being animated, but the start of animation was janky because it didn’t expect it. will-change provides the hint to the browser. More information is always better than less information.
How do I use it?
Specify the will-change property with a value of auto, scroll-position, contents, or another property.
- This is the default. You should specify a better value.
- You’re going to animate the scroll position of the element. The browser may decide to render parts of a scrollable element that aren’t currently visible so that when the user scrolls, they’ll be quickly displayed.
- You’re going to change the contents of an element. Browsers save the contents of elements because they’re not going to change so there’s no point in redrawing. But if you’re going to constantly change the contents of an element, saving contents is a waste of time and memory.
- Some CSS property
- e.g. transform, opacity, width, top, left, etc.
- You’re going to change the provided property.
It’s worth noting that this property will have no effect on the element unless the property provided changes the stacking context or containing block. For example, setting opacity changes the stacking context of an element, and position: fixed changes the containing block of an element. But don’t overuse the property, since this could have a negative impact on performance.
Can I use it?
Sure! But no one may hear you. At the time of this post, pretty much just Chrome supports it. Check the current status at caniuse.com.
There’s been a hack in the wild for a while that achieved better rendering performance called the “null transform”. This was achieved by adding the rule transform: translate3d(0,0,0) . This effectively promotes the layer to be rendered on the GPU, making animations happy. Read more about it here: http://aerotwist.com/blog/on-translate3d-and-layer-creation-hacks/.