Javascript ‘memory leaks’
August 15th, 2007Well, we all call them memory leaks, anyway - although they are more like the telltale signature (kind of like William Shatner singing Karaoke) of a garbage-collecting-challenged browser. In addition to reference counting maybe the garbage man should add reachability counting?
Speshy tries and prevents these leakish-like events by by letting JS objects point to DOM objects, and NOT letting DOM objects point to JS objects - except for event handlers, of course.
Event handlers on DOM objects point to JS objects, and we use Prototype’s Event.observe method to cache these event handlers and remove them, calling Event.unloadCache, when no longer needed.
Since our pages are dynamic, we are constantly adding and removing objects, and so we added a method to Prototype, in addition to Event.unloadCache which blasts all event handlers, to blast just those event handlers that are assigned to the DOM object sub-hierarchy we want to remove.
For grins, here it is:
unObserve: function(element) {
if (!Event.observers) return;
element = $(element);
if (!element.sp_oid) return;
element.sp_oid = null;
for (var i = 0; i < Event.observers.length; i++) {
if (Event.observers[i][0] == element)
{
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers.splice(i, 1);
--i;
}
}
},
DOM elements that have been assigned an event handler have their sp_oid attribute set. In order to speed this up some, since the vast majority of elements will NOT have an event handler, and it would be a crying shame to iterate through this loop for each and every one of them in each DOM sub-hierarchy we want to remove, we just quickly return if sp_oid is not set.
It seems to work so far, according to the Drip (a memory leak detector for Internet Explorer) . Not a very ‘Spock’ thing to say, more a Bones-like prevarication, but the probability of an error creeping back in is not close to zero (kind of why we got rid of malloc and free in the first place, right?)
Anyway, hope these insights into the amazing adventures that are our daily life are of interest. Not too many javascript frameworks out there yet…
Enjoy!