reactjs - lottie 文件降低 NextJS 应用程序的性能
问题描述
我在我的 NextJS 项目中使用 lottie JSON 文件来展示其中一些很酷的动画。
问题是 lottie JSON 文件很大,确实会降低应用程序的性能。有没有人找到一种方法来使用这些动画而不会使项目的性能得分减半?
我在我的个人网站(下面的链接)上使用它们,并且 lottie 文件位于服务部分(如果您在下面滚动一下)。初始页面加载感觉有点慢,我真的很想找到解决方案。
解决方案
您可以异步(动态)加载库和动画 json,如下所示:
import { useEffect, useRef, useState } from 'react';
import type { LottiePlayer } from 'lottie-web';
export const Animation = () => {
const ref = useRef<HTMLDivElement>(null);
const [lottie, setLottie] = useState<LottiePlayer | null>(null);
useEffect(() => {
import('lottie-web').then((Lottie) => setLottie(Lottie.default));
}, []);
useEffect(() => {
if (lottie && ref.current) {
const animation = lottie.loadAnimation({
container: ref.current,
renderer: 'svg',
loop: true,
autoplay: true,
// path to your animation file, place it inside public folder
path: '/animation.json',
});
return () => animation.destroy();
}
}, [lottie]);
return (
<div ref={ref} />
);
};
推荐阅读
- c - 如何使用自定义加密服务提供程序 (CSP) 在 Chrome 上进行 SSL/TLS 客户端身份验证
- html - Bootstrap modal 总是跳到页面顶部
- visual-studio-code - 调试时如何在“变量列表”中搜索道具/变量?
- nginx - 自定义 Nginx 反向代理后面的 Meteor 乘客独立
- laravel - Laravel 每天从数据透视表中得到锻炼
- typescript - 使用字符串文字作为计算属性名称的模板参数
- python - 如何修补从另一个模块导入的函数
- android - 将flutter模块添加到android项目时无法触发onActivityResult
- c# - C# BigInteger 按位异或返回额外的数字
- javascript - 更改上下文后使用新数据渲染页面