首页 > 解决方案 > lottie-web 中的内存泄漏

问题描述

我在前端使用lottie web。但我仍然遇到内存泄漏问题。当我删除所有 lottie 时,JavaScript VM 实例小于 10MB。

当我启用lottie时,每当我刷新页面或浏览其他页面时,内存都会迅速增加。从 30MB 到 80 等。然后页面出现延迟。

我发现了这个问题,但解决方案对我来说不正确,因为我的动画不使用中继器。无论如何,我试图这样做,但没有任何结果。

你可以在这里看到整个测试网站

注意:我正在使用 vue 和我的自定义组件来制作乐天动画

<template>
    <div ref="animation"></div>
</template>

<script>
import lottie from 'lottie-web';

export default {
    data() {
        return {
            hover: false,
        }
    },
    mounted() {
        lottie.loadAnimation({
            container: this.$refs.animation,
            renderer: this.renderer,
            loop: this.loop,
            autoplay: this.autoplay,
            path: this.path, // This is where my animations come from.
        });
    },
    props: { /* my props */ }
}

我还尝试通过导入来放置动画:

import animation from '../../../../images/web/ilu-we-create.json';
...
mounted() {
    lottie.loadAnimation({
        container: this.$refs.animation,
        renderer: this.renderer,
        loop: this.loop,
        autoplay: this.autoplay,

        // Without deep copy
        animationData: animation,

        // With deep copy
        //animationData: JSON.parse(JSON.stringify(animation)),
    });
},
...

每个解决方案的内存使用结果几乎相同。

是否有人知道lottie 如何分配内存以及如何避免这些内存泄漏?

十分感谢。

标签: javascriptvue.jsanimationmemory-leakslottie

解决方案


我遇到了同样的问题,可能已经设法解决了(不是专家监控内存泄漏)

我动态导入lottieanimationData喜欢这样.. 不仅调用破坏方法,this.animation.destroy()而且还调用this.lottie.destroy()

...,
  async mounted () {
    this.lottie = await import('lottie-web').then(module => module.default)
    this.animationData = await import('~/path/to/animationData.json')
    this.$nextTick(() => {
      this.animation = this.lottie.loadAnimation({
        animationData    : JSON.parse(JSON.stringify(this.animationData)),
        loop             : false,
        autoplay         : true,
        renderer         : 'svg',
        container        : this.$refs.heroCanvas,
        rendererSettings : {
          progressiveLoad: false,
        },
      })
    })
  },
  beforeDestroy () {
    if (this.lottie) {
      this.lottie.destroy()
      this.lottie = null
    }
    if (this.animation) {
      this.animation.stop()
      this.animation.destroy()
      this.animation = null
    }
  },
...

推荐阅读