Lottie 文件降低了 NextJS 应用程序的性能

Ana*_*dis 5 reactjs next.js lottie

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

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

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

https://stylidis.io

Dan*_*ila 21

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

  • 我的建议也是针对 Next.js,你不需要 `/static` 文件夹,如果你愿意,你可以将它放在 `/public` 中。虽然如果你愿意,你可以把它放在任何地方,比如“/public/static/files/animations/...”等等,但这并不重要。当然,只需相应地更改代码中的“路径”即可。 (2认同)