Search

6/10/2008

Finally, the alternative fix for IE6's memory leak is available

try finally 妙用,防止内存泄漏【转自51js】 - AJAXBBS.NET - WEB前端技术交流博客

Finally, the alternative fix for IE6's memory leak is available
Ajaxian » Is “finally” the answer to all IE6 memory leak issues?

The finally statement defines a block of code that will always be run after the completion of the preceding try block. The finally block will always be run even when an error occurs and control is passed to a catch block. The finally block will be run immediately after any catch block. Finally is a reserved word and cannot be used for anything other than declaring a final error handler for a try block.


function createButton(){
var obj = document.createElement("button");
obj.innerHTML="点我!";
obj.onclick=function(){
//处理click事件
}
obj.onmouseover=function(){
//处理mouseover事件
}
return obj;//这里由于需要返回创建的对象,所以不能把obj直接设为null. return 后obj是局部变量,不能在外部断开其与HTMLElement的引用.ie中将出现问题泄漏问题
}
var 按钮 = document.getElementsById("d1").appendChild( createButton());
按钮.做某些事();
按钮.做某些事();


function createButton(){
var obj = document.createElement("button");
obj.innerHTML="点我!";
obj.onclick=function(){
//处理click事件
}
obj.onmouseover=function(){
//处理mouseover事件
}
try{
return obj;
}finally{
obj = null;//这句话在return 之后才执行 , 的效的解决了需在return后将obj置null的问题
}
}

Finally, the alternative fix for IE6's memory leak is available
Codes that introduces memory leak in IE6

(function (limit, delay) {
var queue = new Array(10);
var n = 0;

function makeSpan(n) {
var s = document.createElement('span');
document.body.appendChild(s);
var t = document.createTextNode(' ' + n);
s.appendChild(t);
s.onclick = function (e) {
s.style.backgroundColor = 'red';
alert(n);
};
return s;
}

function process(n) {
queue.push(makeSpan(n));
var s = queue.shift();
if (s) {
s.parentNode.removeChild(s);
}
}

function loop() {
if (n < limit) {
process(n);
n += 1;
setTimeout(loop, delay);
}
}

loop();
})(10000, 10);


Code that doesn't introduce memory leak in IE6

(function (limit, delay) {
var queue = new Array(10);
var n = 0;

function makeSpan(n) {
var s = document.createElement('span');
document.body.appendChild(s);
var t = document.createTextNode(' ' + n);
s.appendChild(t);
s.onclick = function (e) {
s.style.backgroundColor = 'red';
alert(n);
};

//fix start
try {
return s;
} finally {
s = null;
t = null;
}
//fix end
}

function process(n) {
queue.push(makeSpan(n));
var s = queue.shift();
if (s) {
s.parentNode.removeChild(s);
}
}

function loop() {
if (n < limit) {
process(n);
n += 1;
setTimeout(loop, delay);
}
}

loop();
})(10000, 10);

沒有留言: