Vue - Memory leak with external scripts (non-npm library)

57 Views Asked by At

I using a external javascript library for working with stl files (Stl Viewer) in a vue project. I inject the script in body like that on the mounted function.

...
mounted () {
  const script = document.createElement('script')
  script.setAttribute('src', '/stl_viewer/stl_viewer.min.js')
  document.head.appendChild(script)
}
...

The script works well, but after testing some 3D models with a size > 1MB, the consume of memory increases nonsense, i compare with the preview that the library provides, and in my project it consumes more or less 10x more.

Initially i think i maybe calling the script more than once, then i created states for be sure that this will not happen.

...
mounted () {
    // Verify if script is already loaded
    if (!this.$store.state.stlViewerLoaded) {
      // Load script in DOM
      const script = document.createElement('script')
      script.setAttribute('src', '/stl_viewer/stl_viewer.min.js')
      document.head.appendChild(script)

      // Set that script loaded
      this.$store.dispatch('stlViewerLoaded')

      // Wait for script be ready
      script.onload = this.createInstance

      return
    }
    this.createInstance()
},
methods: {
    createInstance () {
      // Prevent function called more than once
      if (!this.instance) {
        // Obtain script function from window
        // Create Instance
        this.instance = new window.StlViewer(

          // Ref
          this.$refs.viewer,

          // Init parameters
          {
            models: this.models.map((m, i) => ({ id: i, filename: m })),
            display: 'smooth',
            on_model_mouseclick: this.modelClick,
            controls: 1
          }
        )
      }
    },
...
}

I also use beforeDestroy to clear any memory in use on previous pages.

beforeDestroy () {
    if (this.instance) this.instance.dispose()
    this.instance = null
  }

But not of that solve the problem, i also try to called the script directly in index.html, but keeps the same.

I also tried to build the project instead of use npm run serve. But even with deploy the problem persist.

I believe that this script is not optimized for working with frameworks like vue, and i may need to use something like three.js (which has for npm) to have more autonomy.

Is i doing something wrong? Or is a problem with the library?

Thank you so much.

0

There are 0 best solutions below