javascript / expert
Snippet
Tracking Garbage Collection of Action Target Nodes with WeakRef and FinalizationRegistry
This Svelte action uses JavaScript's WeakRef and FinalizationRegistry to monitor DOM node lifecycle and garbage collection without holding strong references that cause memory leaks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export function gcTrackedAction(node, options = {}) {let ref = new WeakRef(node);const registry = new FinalizationRegistry((heldValue) => {options.onGarbageCollected?.(heldValue);});registry.register(node, options.id || 'unnamed-node');return {destroy() {const target = ref.deref();if (target) {registry.unregister(node);}ref = null;}};}
svelte
Breakdown
1
let ref = new WeakRef(node);
Creates a weak reference to the DOM node so garbage collection is not prevented.
2
const registry = new FinalizationRegistry((heldValue) => {
Instantiates a cleanup tracker executing a callback once the registered target is reclaimed.
3
registry.register(node, options.id || 'unnamed-node');
Registers the HTML node with associated metadata for memory monitoring.
4
const target = ref.deref();
Safely checks whether the target DOM node still exists in memory before teardown.