Common Memory Leak Pattern: Detached DOM Nodes
You'll learn how to identify and fix a sneaky memory leak where removed DOM elements stick around in memory because your JavaScript still holds references to them.
What's a Detached DOM Node?
When you remove a DOM element from the page (using removeChild() or remove()), you might think it disappears completely. But if your JavaScript code still holds a reference to that element—in a variable, array, or object—the garbage collector can't free it. The node becomes "detached": removed from the live DOM tree but still alive in memory.
Think of it like deleting a contact from your phone's address book, but keeping their business card in your wallet. They're "removed" from your contacts, but you're still holding onto them.
The Pattern in Action
let hiddenCache = [];
function addItem(text) {
const item = document.createElement('div');
item.textContent = text;
document.body.appendChild(item);
// Store reference for later
hiddenCache.push(item);
}
function removeAllItems() {
document.body.innerHTML = ''; // Removes from DOM
// BUT hiddenCache still has references!
}
After calling removeAllItems(), those divs are gone from the page but not from memory because hiddenCache still references them.
The Fix
Clear your references when removing elements:
function removeAllItems() {
document.body.innerHTML = '';
hiddenCache = []; // Release references!
}
Or better yet, avoid storing DOM references when possible. Use IDs or data attributes to query elements when needed instead of caching them.
Key Takeaway: Detached DOM nodes occur when you remove elements from the page but keep JavaScript references to them—always clear those references to allow garbage collection.