Disposing of memory in THREE JS when switching between routes in VUE

Currently, I am delving into the world of VUE JS and working on a basic SPA that navigates through different pages.

In my spare time, I have developed several THREE JS demos which unfortunately tend to slow down and eventually halt when switching between pages due to memory buildup. I suspect the issue lies not within the scripts themselves, as they are quite extensive, but rather in how I am initializing them and my limited knowledge of VUE JS.

One of the views I am routing to in VUE JS looks like this:

<template>
    <div class="particles">
        <main-menu></main-menu>

        <div id="demo"></div>
    </div>
</template>

<script>
    import mainMenu from 'root/views/menu.vue';

    export default {
        components: { mainMenu },
        mounted() {
            var Particles = require('root/webgl/particles.js');
            var demo = new Particles();
            demo.run();
        }
    }
</script>

The original demos were created using traditional JavaScript (it's an ES5/6 class) and I hoped to seamlessly integrate them into my VUE SPA. In each demo, I am loading shaders and attaching my THREE demo to a DOM element like so:

this.vsParticles = document.getElementById('vs-particles').textContent;

My concern arises from the fact that something is not getting properly cleared or deleted. While my demos function smoothly outside of the SPA context without creating any new elements in the DOM, they accumulate issues once placed within a SPA app and navigating between pages.

I had assumed that changing routes would result in everything being wiped clean - all elements within my template tags and any objects I create within `mounted()`. However, that does not seem to be the case. I am now wondering if there are additional steps I need to take in VUE to ensure complete cleanup between page transitions.

Answer №1

While discussing the issue, Mathieu D. suggested moving the require statement outside of the method.

Additionally, it might be necessary to clear the WebGL context in the destroyed () hook of the Vue Component.

Although I cannot guarantee that this is the best approach, here is how I handle disposal in my program:


    this.renderer.forceContextLoss()
    this.renderer.context = null
    this.renderer.domElement = null
    this.renderer = null

Answer №2

Have you considered importing particles.js outside of the mounted method? Perhaps right after importing mainMenu?

This way, the import would be applied universally across all instances of Particles.

Your code should look something like this:

import mainMenu from 'root/views/menu.vue';
import Particles from 'root/webgl/particles.js';

export default {
    components: { mainMenu },
    mounted() {
        var demo = new Particles();
        demo.run();
    }
}

If you're interested in learning more about reactivity in VueJS, I recommend checking out the documentation on reactivity. Understanding how VueJS stores and accesses data can greatly benefit your development process. If your component code stores data from your ThreeJS examples, it may consume memory. In that case, utilize the destroyed hook to properly clean up your data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

What is the syntax for accessing a dictionary item within a <span> tag using JavaScript?

I'm working on a new functionality for a website that involves using a dictionary to store information about clubs, events, and times. var clubName = {}; var event = {}; var time = {}; var dict = new Map(); dict.set(clubName, "G ...

loading preloaded fonts at the optimal moment

My webfonts are loaded using Webfontloader as shown below: <script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script> <script> WebFont.load({ custom: { families: ['BlenderProBook' ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Sorting an array of elements in JavaScript based on their value relationships

I need help grouping the elements of an array based on their inner array groupings Input: const arr = [ [123, 243], [123, 435], [736, 987], [987, 774], [123, 666], [774, 999], [098, 980], ]; Output: Result = [[123, 243, 435, 666],[736, ...

Issue with Vue.js: While the fade out feature is functioning correctly when using v-show, the fade in functionality

Upon following the documentation found here, I have implemented v-show along with a transition element: https://v2.vuejs.org/v2/guide/transitions.html The fade out animation functions correctly; however, when toggling the visibility of the element to mak ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

Nextjs: where all roads lead back to the homepage

Having an issue in my app where all redirects keep leading back to the homepage. The problem seems to stem from my Navbar.js component, as shown below. Despite adding the required route in the Link tag for next-js, both client and server compilation is suc ...

Adapt the class based on different string inputs

I am facing a challenge where I need to dynamically change the div class based on a variable value. The issue is that the variable can have multiple values that should all be considered as true in my case. isActive: "yes" These values can include: "true" ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

Exiting callback function in JavaScript

Is there a way to retrieve the return value from within a node.js/javascript callback function? function get_logs(){ User_Log.findOne({userId:req.user._id}, function(err, userlogs){ if(err) throw err; if(userlogs){ ...

Attempting to retrieve data from HTML in VueJS using two distinct variables

Here's the issue I'm facing: I have two arrays. The first one, which we'll call A, looks like this: [{id: 2, otherValue: "hello"}] The second array, which we'll call B, looks like this: [{1: {title: "title1", text: "message1"}, 2: {t ...

What is the best way to create multiple AngularJS applications using NodeJS?

Upon completing the tutorial found at https://docs.angularjs.org/tutorial, I was inspired to create a new application on my local machine using AngularJS and NodeJS as the server. To start this new project, I made a separate folder at the same level as th ...

Ways to activate flashlight on mobile using React.Js

Is it possible to control the torch light of a mobile device by toggling a button? https://i.stack.imgur.com/x9nIf.png <IconButton onClick={() => setFlashOn(!flashOn)} style={{ position: "absolute", right: 80, top: 20, zIndex: ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

After closing and reopening the jQuery modal, the name does not appear

I crafted a custom modal window to display images along with comments and the owner's name. The issue arises when I close the current modal and reopen it; the owner's name disappears. Oddly enough, the name is displayed the first time the modal i ...

The command "npm run build:css " is not functioning properly, but when I execute the script independently, it works fine

Recently, while working on a program using npm script on my Mac system, I encountered some issues. Despite having installed node-sass globally, running "npm run build:css" did not work as expected. The content of my package.json file can be viewed here. Th ...

instructions for executing this javascript within the <p> tag

This is the code I have written : <p onload=javascript:alert('sss')>www</p> Unfortunately, the code does not alert 'sss', Can someone please tell me what's wrong with my code? Thank you ...

The property 'matMenuTrigger' cannot be attached to 'a' because it is not recognized

Trying to implement matMenuTrigger but encountering an error saying "Can't bind to 'matMenuTrigger' since it isn't a known property of 'a'". Any assistance would be greatly appreciated. ...