JavaScript Performance JavaScript Performance

Applying will-change with JavaScript

Check out a free preview of the full JavaScript Performance course:
The "Applying will-change with JavaScript" Lesson is part of the full, JavaScript Performance course featured in this preview video. Here's what you'd learn in this lesson:

will-change indicates to the browser that a CSS property is likely to change in the near future. JavaScript is typically the change agent and can let the browser know beforehand that it's getting ready to change a property on an element.

Get Unlimited Access Now

Transcript from the "Applying will-change with JavaScript" Lesson

[00:00:00]
>> Steve Kinney: So yeah, it's a CSS property, but most of the time when you're using it, you're gonna use it in JavaScript. You're gonna go in there and say, hey FYI, I know the user is about to do something, but we are going to want to animate this. Let's get it to its own layer now and be good to go.

[00:00:15] So, for instance we could say on mouse enter element.style.willChange, transform will promote it to its own layer, and then when they go, by the time we get it ready to do the thing, then it's already on its own layer, we're good to go. So, if it's like a sidebar or the sticky bottom, use CSS.

[00:00:34] But if it's something that's only going to become its own layer temporarily as you do some animation and then it's going back to a static position, we'll add the willChange, we'll do the thing and then we'll put it back. And again, after we're done we wanna clean up after ourselves, because if they hover over it once and mouse enters, make its own layer.

[00:00:54] And you forget to put it back down, you're gonna end up with a lot of layers. We talked about that's a bad thing. So here's an example, okay, mouse enter, all right? Yeah let's set the transform and then may be when the animation ends, right, put it back down.

[00:01:14] All right, we're done, it doesn't need to be its own layer anymore, we're good to go. All right, so we can do it then. And then I arguably, it would be really extra bonus points, you should have this as well, is like on a mouse leave, also put it down.

[00:01:26] Mouseenters, this would be a box that moves when they click on it, all right? Mouseenters, let's move it to a zone layer, they clicked? Cool, do the animation. Animation's done? Put it back down, the mouse's left? Put it back down, right? And because we are not doing anything else, when the mouseenters, yeah, we are doing some work, but we are doing that work before it is needed.

[00:01:46] We wait until we are ready to start animating, it could look a little jolty, cuz it's like my God I gotta get this to its own layer. And now I've gotta move it, right, versus move it before you need it or move it to it's own layer before you need it, animate it when you're supposed to.

[00:01:59] Put it back down when you're done.