How to optimize performance of css animation
In modern front-end development, CSS animations are powerful tools for improving user experience and interface interactivity, but if used incorrectly, they can also cause performance issues, especially on complex pages and low-performance devices. Therefore, it is important to properly optimize CSS animations to ensure smooth and smooth animations.
Here are some common CSS animation optimization tips that will allow you to demonstrate both your understanding of animation and your acumen for performance optimization during interviews.
1. Avoid using properties that affect reflow and redraw
In CSS animations, certain properties trigger reflow (reflow) and Redraw (repaint), these will cause browser performance to decrease.
Avoid animating the following properties:
width,height: Changing the size of an element will cause reflow.top,left: Changing the position of elements will affect the layout and may trigger reflow.padding,margin: These will affect the arrangement of surrounding elements and also cause reflow.border: Border changes will also cause reflow and redraw.
Prefer using the following properties for animation:
transform: will only trigger redraw and will not cause reflow.Using transform animations such astranslate,scale, androtatecan greatly improve performance.opacity: Changing the transparency will not affect the layout, nor will it cause reflow, which is usually a performance-friendly animation.
Example:
/* 好的动画,使用 transform 和 opacity */
.element {
animation: move 1s ease-in-out;
}
@keyframes move {
0% {
transform: translateX(0);
opacity: 1;
}
100% {
transform: translateX(100px);
opacity: 0.5;
}
}2. Use will-change to inform the browser in advance
will-change is a CSS property that tells the browser in advance which properties you are going to change, thereby optimizing rendering performance.
Time to use:
- Use
will-changeonly if the element needs to animate or transition within a short period of time. - Excessive use of
will-changecan lead to increased memory usage because it triggers hardware acceleration.
Example:
.element {
will-change: transform, opacity;
}Note:
- Only use
will-changewhen needed, overuse will lead to performance degradation. - After using it, make sure to remove
will-changeafter the animation ends.
3. Use hardware acceleration (transform + opacity)
Hardware acceleration improves rendering efficiency by offloading elements to the GPU for processing, avoiding CPU rendering.
How to enable hardware acceleration:
- Use
transform(liketranslate3d) instead ofleft,topandposition. - Use
opacityfor transparency changes, notvisibility.
Example:
/* 使用 transform 进行平移,而不是改变 left/top */
.element {
transform: translate3d(0, 0, 0); /* 使用 translate3d 激活 GPU 加速 */
}Principle:
- The function of
translate3d(0, 0, 0)is to force the browser to hand over the element to the GPU for rendering (i.e. hardware acceleration). - This does not change the element's position, it just triggers hardware acceleration.
4. Use requestAnimationFrame for JavaScript animation optimization
Although this question is mainly about CSS animations, for complex animations, JavaScript animations (such as using requestAnimationFrame) can also be used with CSS animations to better control the frame rate.
Why use requestAnimationFrame:
- It is called on every frame of the browser, providing smooth animation effects, and it automatically optimizes the frame rate of the animation to avoid over-rendering.
- Using
requestAnimationFrameallows you to have more fine-grained control over the start, pause, termination, etc. of the animation.
Example:
let start = null;
function animate(timestamp) {
if (!start) start = timestamp;
let progress = timestamp - start;
document.querySelector('.element').style.transform = `translateX(${Math.min(progress / 10, 300)}px)`;
if (progress < 3000) { // 动画持续3秒
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);5. Avoid overuse of animation
- Limit the number of animations: Running multiple animations at the same time will consume more resources and lead to performance degradation.Reduce the number of animations on the page and keep it simple.
- Reduce animation duration: Each animation does not need to be maintained for a long time, usually 300-500ms animation effect is smooth enough.
- Only optimize user interaction animations: Interactive animations such as clicks and hovers are usually the focus of user attention. Other unimportant animations can be considered disabled.
6. Animation performance testing and tuning
Tools:
- Chrome DevTools Performance Panel: View the performance bottlenecks of CSS animations and find out which animations or style calculations are causing performance bottlenecks.
- Lighthouse: Analyze the animation and rendering performance of the page and provide optimization suggestions.
Check animation smoothness via Lighthouse:
Lighthouse will provide indicators such as FCP (first content draw), LCP (maximum content draw), CLS (layout offset) of the page, which can effectively help you evaluate the impact of animation on page performance.
Summary
Key points for animation performance optimization:
- Avoid using properties that trigger reflow and redraw (
width,height,top,left, etc.), prefertransformandopacity. - Use
will-changeto predict which attributes will change to help the browser optimize rendering. - Enable hardware acceleration and use
transformandopacityinstead of traditional layout properties. - For complex animations, use
requestAnimationFrameto control the frame rate and improve animation smoothness. - Reduce unnecessary animations, avoid too many animations running at the same time on the page, and keep the page simple.