如何在javascript中卸载动态导入?

发布于 2025-01-18 08:31:22 字数 349 浏览 1 评论 0原文

基本上,我有一个 json 文件,它定义用户登录时要加载的内容。这包括 javascript 文件。当不同的用户登录时,需要卸载以前的东西,而无需刷新页面。

我正在利用

 modules[moduleId] = await import(url);

我发现的javascript动态导入,即使我将“模块”变量清除为空对象后,动态导入模块中定义的事件侦听器仍然会触发。我假设该闭包中定义的大多数其他内容仍然占用内存。

现在,如果我像这样滥用登录/注销,我假设我最终会遇到内存泄漏问题。如何确保加载到对象引用中的模块在不再需要时正确卸载?

我在这里使用纯js,无法访问外部库或工具。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开浅夏 2025-01-25 08:31:23

我只能想到一种可能的(相当)好的解决方案。
只需用空模块覆盖该模块即可。
就像,加载将是:

modules[moduleId] = await import(`./${moduleId}.js`);

卸载就像:

modules[moduleId] = await import(`./empty_module.js`);

甚至更好:

modules[moduleId] = null;

编辑: 在测试了许多进行垃圾收集以清理内存的方法之后 - 卸载已加载的模块似乎是不可能的。看来浏览器无论如何都会根据模块的 URL 来缓存该模块。我在 Chromium 上对其进行了测试,以便清楚地了解该主题。所以总而言之 - 通过 import() 加载的模块仍然无法卸载。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文