Interesting way to fix memory leaks in IE6 javascript
Although we should all have updated to at least IE7 by now (if not a more recent competitor), there are still thousands of users out there still stuck in IE6 land. Javascript objects on IE6 are notorious for memory leaks which can seriously degrade performance over time, but I noticed a post over at Ajaxian explaining a very simple workaround using a rarely used javascript construct – try … finally.
So while the following code would leak memory through the return obj;
function createButton() {
var obj = document.createElement("button");
obj.innerHTML = "click me";
obj.onclick = function() {
//handle onclick
}
obj.onmouseover = function() {
//handle onmouseover
}
return obj;//return a object which has memory leak problem in IE6
}
var dButton = document.getElementsById("d1").appendChild(createButton());
//skipped...
Putting the try … finally construct in will fix your memory leak problems:
function createButton() {
var obj = document.createElement("button");
obj.innerHTML = "click me";
obj.onclick = function() {
//handle onclick
}
obj.onmouseover = function() {
//handle onmouseover
}
//this helps to fix the memory leak issue
try {
return obj;
} finally {
obj = null;
}
}
var dButton = document.getElementsById("d1").appendChild(createButton());
//skipped...
There are more demos and proof of concepts over at the blog of Hedger Wang.