Performance
-
Smooth animations must run at 60fps without frame drops.
-
When we animate an element, the browser's renderer needs to do below steps:
- Layout: Calculate the size and position of elements on the page.
- Paint: Draw the page into graphical layers - essentially individual images that make up the page.
- Composite: Draw these layers to the viewport.
-
Animating properties like
padding,margin, andheightwill cause the browser to recalculate the layout of the whole page, which is expensive and might cause dropped frames depending on how much of the layout is affected. -
To get around these problems, animate as much as possible with
transformandopacity. These only trigger the composite rendering step, while layout properties trigger all three render steps.- For example, when scaling elements use
{css} transform: scale()instead of manipulating padding, height etc.
- For example, when scaling elements use
Transforms don't trigger layout recalculation as they only affect the visual representation of an element, not its position in the document flow.
- CSS animations are generally more performant over JavaScript animation, as JavaScript always runs in the main thread.
- Some CSS and WAAPI animations are hardware-accelerated, improving performance. For example,
transformin CSS will likely be hardware-accelerated.
- When the main thread is busy doing other work, JavaScript animation will struggle. The solution is to move to CSS animations in such cases.
In this case, the JS animation drops frames as page routing is happening as well simultaneously.
-
If you have a CSS animation that is running into dropped frames, try using will-change property. This tells the browser to always use GPU rendering for an element property change. Do not use this unless you're running into performance issues already, and use this as a last resort!
.element { will-change: transform, opacity; }