This is an contrived example of how to dispose of DOM objects and DOM Level 2 events by listening for and handling the unload event. View this example in IE5.5 or 6.x. Though this example works in Firefox, memory management is really only a major issue in IE.

To correctly dispose of DOM objects and free up memory, you need to first unhook the event handlers associated with each element and then remove the element from the DOM. Keep in mind that when you remove a child from the DOM ( i.e. removeChild ), though you've removed it, it is still in memory. So, you need to mark it for garbage collection, by nullifying it.

The example works like this. First, startup a memory viewer like Process Explorer and attach it to the browser. Make note of the memory. Now, press "Start". When we press "Start", we create 10,000 div elements. This will lock up your browser for about 10 - 20 seconds. So, don't be alarmed. Unlike this example, we use the DOM Level 2 method for attaching the click event and delegating that to the target/source element. So, instead of 10,000 event handlers, we're only dealing with one. We'll notice that the memory doesn't spike up.

Once the statically positioned elements appear, you can remove them and their DOM Level 2 events by going to a different URL or simply refreshing the browser. This works because the current page listens for the unload event. The unload event's handler removes the event and the nodes from the DOM. Observe how the memory drops close to where it started. View and save the source to study the code.

-- Oliver