views:

87

answers:

1

Hi,

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

+1  A: 

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

Steven Paligo
thank you for the clean explanation. The thing which is not clear for me yet is, when the page unloads, why the DOM is still there. I mean If there is no page to talk about after the unload, why the Browser still keep the DOM of that page in the memory?
burak ozdogan
The DOM exists as a collection of objects in the memory heap of the browser's process. It's not like the DOM is a single entity that the browser can just throw away. (The exception is with browsers that spawn a separate process for each tab. In those cases, the browser can clean everything up by killing the process and letting the OS reclaim the memory.)Anyway, when the page unloads the "DOM" is gone, but pieces of it may remain due to circular references. It's not that the browser wants to leave them behind, it just can't clean them up because it thinks there are still references to them.
Steven Paligo