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; } }
*/