首页 > 解决方案 > lottie 文件降低 NextJS 应用程序的性能

问题描述

我在我的 NextJS 项目中使用 lottie JSON 文件来展示其中一些很酷的动画。

问题是 lottie JSON 文件很大,确实会降低应用程序的性能。有没有人找到一种方法来使用这些动画而不会使项目的性能得分减半?

我在我的个人网站(下面的链接)上使用它们,并且 lottie 文件位于服务部分(如果您在下面滚动一下)。初始页面加载感觉有点慢,我真的很想找到解决方案。

https://stylidis.io

标签: reactjsnext.jslottie

解决方案


您可以异步(动态)加载库和动画 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} />
  );
};

推荐阅读