views:

226

answers:

1

I have a JavaScript widget that is hosted on websites. This widget tracks state in a number of variables in its local namespace. Moreover, it attaches listeners for several events, such as mouse movement.

Should I explicitly destroy both state-tracking variables and detach event listeners on window unload? Or is it ok to rely on the browser to do a good job of cleaning up after the user leaves the page that hosts my widget?

+1  A: 

Once you get rid of the window you get rid of everything in it. Hence, no need to do your own garbage collection. If a certain browser has a memory leak, that is not your fault and your explicit garbage collection probably wouldn't help anyway.

Robusto
Please give a reason for down-ranking an answer!
Bilal Aslam
@Bilal: In a perfect world, they would. This was just a drive-by shooting, and unfortunately that kind of thing happens on this board from time to time.
Robusto
+1 to counteract the anti-socials.
jball
In a perfect world, memory leaks wouldn't exist. Unfortunately, we (and more important: our users) still use browsers that leak memory. I think you should at least do some manual garbage collection: http://javascript.crockford.com/memory/leak.html (no downvote from me, BTW).
Marcel Korpel
@Marcel: The OP is asking whether garbage collection before window.unload is necessary. Everything associated with the page gets dumped at that point. I agree that if you are keeping a page active you should do some garbage collecting, but garbage collection before dumping the page is, IMO, kind of like sorting paper files alphabetically before throwing them away.
Robusto
I reread the question, and he really asks if he should throw away event handlers and the like *on* window.unload. And I really think he should at least detach event handlers. At least with IE6 you get horrible memory leaks when you don't do that with lots of event handlers. Saying it is not our fault that browsers leak ignores a problem many users will suffer from, which you can actually solve. That said, it is very hard to prevent all leaks with a buggy browser like IE6.
Marcel Korpel