Since we might or might not have control over the web page loaded in our Web Browser control based application, so for the web pages
A) Code for those web pages on which we have control
B) Code for those web pages on which we don't have control
A) Code for those web pages on which we have control:
We will have to systematically implement points mentioned below. Following are the two points that should be taken care off while coding on client side
1)We can and should perform a clean up by implementing the rules mentioned in
Leak Patterns by Justin Rogers
2)Bad JQuery programming technique can also bring the application to a halt and so there is a great solution that i felt should also be included in the clean up approach
JQuery GarbageCollection
B) Code for those web pages on which we don't have control:
We will have to systematically implement a series of functions which should be called at Page UnLoad. Following are the two points that can be included in the
1) Event handling clean up manager method will keep track of all the added events and On unload, it can unregister all the handlers.
something like this
function ReleaseHandler() {
var EvtMgr = (function() {
var listenerMap = {};
// Public interface
return {
addListener: function(evtName, node, handler) {
node["on" + evtName] = handler;
var eventList = listenerMap[evtName];
if (!eventList) {
eventList = listenerMap[evtName] = [];
}
eventList.push(node);
},
removeAllListeners: function() {
for (var evtName in listenerMap) {
var nodeList = listenerMap[evtName];
for (var i = 0, node; node = nodeList[i]; i++) {
node["on" + evtName] = null;
}
}
}
}
})();
}
2) For dereferencing function, the purge function will be passed a reference to a DOM element as an argument like this
purge(document.body)
It loops through the element's attributes. If it finds any functions, it nulls them out. This breaks the cycle, allowing memory to be reclaimed. It will also look at all of the element's descendent elements, and clear out all of their cycles as well. The purge function is harmless on Mozilla and Opera. It is essential on IE. The purge function should be called before removing any element, either by the removeChild method, or by setting the innerHTML property.
function purge(d){
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0 ; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
Note: The biggest reason for this Memory Leak in IE and IE based controls (Like Web Browser Control) is because there is a separate garbage collector for the DOM and for javascript.