Reputation: 81
So basically, I have a json file that defines what to load when a user logs in. This includes javascript files. When a different user logs in, the previous stuff needs to be unloaded without a page refresh.
I'm making use of the javascript dynamic import
modules[moduleId] = await import(url);
I'm finding, that even after I clear the "modules"-variable in to an empty object, the event listeners defined within the dynamically imported module are still firing. I'm assuming most everything else defined within that closure is still taking up memory also.
Now if I were to abuse the login/logout like this, I'm assuming I would end up with memory leak issues. How do I make sure the modules loaded in to an object reference are properly unloaded when they are no longer needed?
I'm working with pure js here with no access to outside libraries or tools.
Upvotes: 8
Views: 2541
Reputation: 51
I can think of only one possible (fairly) good solution. Just overwrite the module with empty one. Like, loading would be:
modules[moduleId] = await import(`./${moduleId}.js`);
Unloading being like:
modules[moduleId] = await import(`./empty_module.js`);
or even better:
modules[moduleId] = null;
Edit: After testing many ways to make garbage collection to clean up memory - it appears impossible to unload a loaded module. Appears that the browser caches the module no matter what, based on it's URL. I tested it on Chromium, to be clear on the topic. So all in all - loaded module through import() is still impossible to be unloaded.
Upvotes: 4