0

All:

When I try to follow a JS DOM memory leak tutorial, there is one example of memory leak about 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>

And the solution it gives is:

<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>

My confuse here:

  1. What is the leak: the myBtn DOM object or the onclick function?(my understanding: it tries to say the DOM, because that innerHTML tries to replace the whole button node with a text node)
  2. If the DOM is the leak, then that btn variable still references to the DOM, which causes it can not be GCed, why this can be the solution?

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

1 Answers1

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.

Angel Luis
  • 322
  • 4
  • 14
  • Thanks, that is also what I thought, thanks for clear. It makes me confused, cos the second part code marked as solution in the post I read. – Kuan Apr 26 '18 at 17:04