我是否必须清除 window.onunload 事件上的自定义属性 (Expandos)?
在一篇文章中,我看到最好清除 window.unload 事件上的所有 Expando 以防止内存泄漏。
我不明白为什么要这样做。
一旦你离开页面,浏览器不是会清理所有 DOM 及其相关资源吗?
谢谢,
布拉克·奥兹多安
In one article I have seen that it may be good to clear all expandos on window.unload event to prevent memory leaks.
I cannot understand why to do this.
Isn't the browser cleaning all the DOM and its relevant resources of it once you leave the page anyway?
Thanks,
burak ozdogan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嘿,好问题。问题在于 JavaScript 对象和 DOM 节点之间的循环引用。
假设您有一个指向 DOM 节点的全局 JavaScript 对象,并且该节点有一个指向该对象的 Expando 属性。当页面卸载时,脚本引擎“清空”JavaScript 对象,使其不再指向 DOM 节点。但是,它无法从内存中释放该对象,因为仍然存在对它的引用(来自 DOM)。然后脚本引擎终止。
DOM 上的 Expando 属性只不过是对其他对象的引用。当 DOM 被清理时,它会破坏这些引用,但假设这些对象仍在使用中。在此示例中,DOM 等待脚本引擎清理属于它的对象,但脚本引擎已经终止。
因此,问题在于 DOM 只处理属于它的内存,并假设脚本引擎也会做同样的事情。
我希望这有帮助。
请参阅:http://msdn.microsoft.com/ en-us/library/bb250448%28VS.85%29.aspx
Hey, great question. The problem is with circular references between JavaScript objects and DOM nodes.
Let's say you have a global JavaScript object which points to a DOM node and the node has an expando property back to the object. When the page unloads, the script engine "nulls-out" the JavaScript object so it no longer points to the DOM node. But, it cannot release the object from memory because there is still a reference to it (from the DOM). Then the script engine terminates.
Expando properties on the DOM are nothing but references to other objects. When the DOM is being cleaned up, it breaks those references but assumes that the objects are still being used. In this example, the DOM waits for the script engine to clean up the objects that belong to it, but the script engine has already terminated.
So, the problem is that the DOM only takes care of the memory that belongs to it and assumes the script engine will do the same.
I hope this helped.
See: http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx