How can Detached DOM elements cause memory leak in JavaScript?


Detached Dom elements

Detached DOM elements are the elements which have been removed from the DOM but their memory is still retained because of JavaScript. This means that as long the element have a reference to any variable or an object anywhere, it does not garbage collected even after destroyed from the DOM.

DOM is like an double-linked tree which means a reference to a node in the tree will halt the entire tree from garbage collection.

Let's take an example of creating a DOM element in javascript. After creating the element destroy it but forget to delete the variable holding it. This scenario leads to a Detached DOM which has a reference not only to the particular DOM element but also to the entire tree.

Example

In the following example, even after removed from the DOM, 'someText' will still have a reference in the global 'value' object.This is why it can't eliminated from garbage collector and continue to consume memory.This causes memory leak.

<html>
<body>
<script>
   var example = document.createElement("p");
   example.id = "someText";
   document.body.appendChild(example);
   var value = {
    text: document.getElementById('someText')
   };
   function createFun() {
      value.text.innerHTML = "Javascript is not Java";
   }
   createFun();
   function deleteFun() {
      document.body.removeChild(document.getElementById('someText'));
   }
   deleteFun();
</script>
</body>
</html>

Avoiding memory leak

To avoid memory leak, the best practice is to put var example inside listener, which makes it a local variable. When var example is deleted the path for the object will cutoff,allowing the garbage collector to release memory.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements