How to unload dynamic imports in javascript?
Asked Answered
M

1

8

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.

Mcgruter answered 30/3, 2022 at 21:51 Comment(1)
There is no memory leak from calling import several times since importing an already-loaded module will not load it again but simply return the existing instance. If you have event listeners in there though, then you need to call some function that unregisters them.Tabret
B
4

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.

Blate answered 11/9, 2022 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.