Find detached DOM nodes in a heap snapshot
Locate DOM elements kept alive after removal by taking a heap snapshot in Chrome DevTools and filtering the class list for Detached.
A detached node is an element removed from the page that JavaScript still references, so it cannot be freed. This code leaks one:
const cache = [];
function openPanel() {
const el = document.createElement("div");
document.body.append(el);
cache.push(el);
el.remove();
}Each call leaves a div in cache that is no longer in the document. To find them, open the Memory panel, choose Heap snapshot and take a snapshot after calling openPanel() a few times. In the filter box, type Detached:
Detached HTMLDivElementExpand the entry and its Retainers pane lists what holds the node: here, an index of the cache array. That path is the fix, since you must drop that reference. See Fix memory problems for the workflow.
Event listeners, timers and closures are the usual holders. Detached nodes keep their children and any data attached to them, so one small leak can hold a large subtree.
Take the snapshot after forcing garbage collection with the trash can button, so you see only nodes that really cannot be freed.