所有
当我尝试关注JS DOM内存泄漏教程时,有一个关于 OLD IE (7,8)的内存泄漏示例:
<div id="myDiv">
<button id="myBtn">Click Me</button>
</div>
<script type="text/javascript">
var btn = document.getElementById("myBtn");
btn.onclick = function(){
document.getElementById("myDiv").innerHTML = "Processing...";
}
</script>
它给出的解决方案是:
<div id="myDiv">
<button id="myBtn">Click Me</button>
</div>
<script type="text/javascript">
var btn = document.getElementById("myBtn");
btn.onclick = function(){
btn.onclick = null;
document.getElementById("myDiv").innerHTML = "Processing...";
}
</script>
我在这里感到困惑:
btn
变量仍然引用DOM,这导致它无法进行GC,为什么这可以作为解决方案?由于
答案 0 :(得分:2)
The leak are in both cases. You have to free the btn
variable pointing to a DOM object and the onclick
event to stop listening that event.