Search code examples
javascriptgarbage-collectioncross-browser

Remove DOM element explicitly to avoid memory leakage in javascript


I was checking the doc in MDN about garbage collection. When I come across the 'Real-life example' section, the term 'explicitly removed' in below statement confused me.

If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in memory even if it was removed from the DOM tree

Can document.removeChild fulfill the criteria of removing DOM element explicitly?


Solution

  • Can document.removeChild fulfill the criteria of removing DOM element explicitly?

    The question indicates some confusion: there is no criteria to explicitly remove the DOM node. Removing an element from the DOM, either explicitly or implicitly (by removing an ancestral element from it descends), should make it available for memory collection assuming no reference to the removed element is retained in code. The property mentioned at the beginning of the quoted article refers to the div.circularReference property used in the example, whose value was set to div to create a circular reference back from the property to the element.

    Explicitly removing "the property" could be achieved by deleting or changing the property's value, for example with

     div.circularReference = null; // or
     delete div.circularReference;
    

    Removing the circular reference could be done before or after removal of div from the DOM. The good news is where the article says reference-counting garbage collector are no longer used in modern browsers.