LottieFiles集群7 分钟阅读·ExodeUI 团队
在 React 中优化 Lottie:减少捆绑包大小和 CPU 消耗
了解如何优化 React 应用程序中的 Lottie 动画、减少 JavaScript 捆绑包影响以及将静态 JSON 迁移到交互式 ExodeUI 状态机。
直接总结和定义
核心要点
使用lottie-web或lottie-react在React中运行Lottie意味着加载一个解析动画JSON并逐帧渲染它的播放器。对于小型装饰动画,普通的CSS往往更轻一些;对于交互式运行时,基于状态的运行时(例如 ExodeUI 或 Rive)可能更适合。测量任何更改之前和之后的包大小和 CPU。
Lottie 对核心 Web 生命体的影响
在初始页面加载期间执行 Lottie 动画时,经常会触发总阻塞时间 (TBT) 和最大内容绘制 (LCP) 回归。由于 Lottie 评估 JavaScript 中每一帧的矩阵变换,因此低功耗移动设备会遭受严重的电池消耗和帧丢失。
生产实施片段
交互组件实现
// A small decorative "like" pop in plain CSS instead of a Lottie file.
// No player needed; measure your own bundle and CPU before and after.
export function LikeHeart({ active }) {
return (
<svg className={active ? 'heart heart--active' : 'heart'} viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 21s-7-4.4-9.3-8.6C1 9.2 3 5.5 6.6 5.5c2 0 3.4 1.1 4.4 2.5 1-1.4 2.4-2.5 4.4-2.5 3.6 0 5.6 3.7 3.9 6.9C19 16.6 12 21 12 21z" />
</svg>
);
}
/* CSS
.heart { fill: #ccc; transition: fill 150ms; }
.heart--active { fill: #ff4a1c; animation: pop 320ms cubic-bezier(.2,1.6,.4,1); }
@keyframes pop { 0% { transform: scale(1); } 50% { transform: scale(1.25); } 100% { transform: scale(1); } }
@media (prefers-reduced-motion: reduce) { .heart--active { animation: none; } }
*/