All:
While attempting to learn about memory leaks in JS DOM, I came across an example specifically related to 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>
The suggested solution is as follows:
<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 confusion lies here:
- Is the memory leak related to the myBtn DOM object or the onclick function?(my interpretation: it seems to suggest the DOM, as innerHTML replaces the button node with a text node)
- If the DOM is causing the leak, then the
btn
variable still holds reference to the DOM, preventing it from being garbage collected. Why is this considered a solution?
Thank you