

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- How can closures cause memory leak and how to prevent it?
- How can circular references cause memory leakage in JavaScript?
- How can Forgotten timers or callbacks cause memory leaks in JavaScript?
- What is Memory Leak in C/C++?
- What is DNS Leak (IP Leak)?
- Can a microwave cause cancer?
- How can I remove all child elements of a DOM node in JavaScript?
- How to allocate memory in Javascript?
- Memory Management in JavaScript
- How are variables allocated memory in JavaScript?
- What can cause a Cannot find symbol error in java?
- Eradicating Memory Leaks in Javascript
- How to free up the memory in JavaScript?
- How to remove DOM elements in jQuery?
- What is the cause of NoSuchElementException and how can we fix it in java?