Would 'will-change' applied via the Web Animations API have the desired effect?

267 Views Asked by At

According to Google:

The general rule of thumb is that if the animation might be triggered in the next 200ms [...] then having will-change on animating elements is a good idea. For most cases, then, any element in your app’s current view that you intend to animate should have will-change enabled for whichever properties you plan to change.

So my question is, can will-change be applied via the Web Animations API before any property is actually animated, and will that have the desired effect? Or is that too late in the lifecycle of whatever's going on behind the scenes for will-change to work properly?

It seems like properties modified via this API aren't actually reflected in DevTools as CSS properties, so I can't verify whether this actually even applied will-change at all.

Example of the idea:

this.animation = document.querySelector('#my-element').animate(
  [
    {
      willChange: 'opacity', // will-change applied before any animated property has been changed
      opacity: 'initial',
    },
    {
      willChange: 'opacity',
      opacity: 'initial',
      offset: 0.01, // 1% of the way through the animation
    },
    {
      willChange: 'opacity',
      opacity: 0.5,
      offset: 0.5, // 50% of the way through the animation
    },
    { 
      willChange: 'initial',
      opacity: 'initial'
    },
  ],
  1000
);
2

There are 2 best solutions below

8
Slbox On BEST ANSWER

It looks like will-change is actually completely unnecessary when using WAAPI (Web Animation API.)


if you have a delay on your animation, you don’t need to worry about using will-change. -- Source

From one of the authors of the spec:

If you have a positive delay, you don’t need will-change since the browser will layerize at the start of the delay and when the animation starts it will be ready to go.

5
brianskold On

Yes, it will have the desired effect.

Animations affect an element's computed style, but many DevTools panels present the element's specified style, hence why you don't see it there.

An alternative approach is to simply add a short delay to the animation. During the delay phase of the animation, the browser is required to apply will-change: opacity (or whatever other properties are being animated). (Spec reference)

That said, there is really no advantage to doing so. The purpose of applying will-change is to let the browser prepare the content for animating (e.g. by re-rasterizing it as separate layers) so that the animation starts without delay. If you simply start the animation as normal, the browser will re-rasterize as necessary and then begin the animation from the start.

The advantage to using will-change is if you know before you need to start the animation which element you are going to animate, you can let the browser doing that preparation ahead of time.