可以卸载动态加载的 JavaScript 吗? [英] Can dynamically loaded JavaScript be unloaded?
问题描述
我正在编写一个具有静态外部外壳"和动态内容部分的 Web 应用程序.当用户浏览系统时,动态内容部分有许多更新.当加载一个新的内容块时,它也可以选择加载另一个 JavaScript 文件.以良好的内务管理为名,我从 DOM 中删除了适用于旧内容块的脚本块,因为不再需要该 JavaScript.
I am writing a web application that has a static outer "shell" and a dynamic content section. The dynamic content section has many updates as users navigate the system. When a new content block is loaded, it may also optionally load another JavaScript file. In the name of good housekeeping, I remove script blocks from the DOM that apply to old content blocks, since that JavaScript is no longer needed.
接下来问题来了,当我意识到虽然我已经从 DOM 中删除了 元素,但之前评估的 JavaScript 仍然可以执行.这当然有道理,但我担心如果用户导航到许多不同的部分,它可能会导致内存泄漏.
The problem comes next, when I realized that although I have removed the <script>
element from the DOM, the JavaScript that was previously evaluated is still available for execution. That makes sense of course, but I'm worried that it may cause a memory leak if the users navigate to a lot of different sections.
那么问题来了,我应该担心这种情况吗?如果是这样,有没有办法强制浏览器清理过时的 JavaScript?
The question then, is should I be worried about this situation? If so, is there a way to force the browser to cleanup stale JavaScript?
推荐答案
您可以采用更面向对象的方法,并以每个块的方式构建模型javascript 块作为自己的对象出现,有自己的方法.卸载它后,您只需将该对象设置为 null
.</theory>
<theory>
You could go with a more object-oriented approach, and build the model in a way that each block of javascript blocks come in as their own objects, with their own methods. Upon unloading it, you simply set that object to null
.</theory>
这篇关于可以卸载动态加载的 JavaScript 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!