博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

IE6:内存泄露

Posted on 2008-12-18 16:49  周末  阅读(231)  评论(0编辑  收藏  举报

问题产生

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.getElementById("d1").appendChild(createButton());
//skipped.

对于 IE6 中,引起内存泄露的原因,可看《Understanding and Solving Internet Explorer Leak Patterns》一文。

上面的例子,应该属于上文中的 “Closures”原因。

解决方案:

/**
     * Use the try  finally statement to resolve the memory leak issue
*/
 
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.getElementById("d1").appendChild(createButton());
//skipped.