This is not actually possible / you cannot influence this much but you can keep constructing and deconstructing somewhat clean.
.deconstrucor() is called when cleaning a branch IN REVERSE order from child to parent
Because JS cannot know that we remove the route / branch you shall handle all manually run services here like an animation loop
TODO
to be tested as they are not attached. They will run forever until you go Worker.terminate(). Watch out for atomic mutex locks as those will not clear automagically.
Only for custom elements!!! Use mutationobservers for normal HTMLElements!!!
These have methods that will run when you add them in any depth to any document.-Element (that is the root of the current page, so <html>).
.connectedCallback() runs when
- DOM Insertion: `parent.appendChild(el)`, `parent.append(el)`, `parent.prepend(el)`, `parent.insertBefore(el, ref)`
- Replacement: `oldEl.replaceWith(newEl)`, `parent.replaceChildren(...)`
- Parser parsing: When the browser HTML parser instantiates the tag from static HTML at first page load. This is rather obvious but for completion
Watch out:
- Children might not exist yet: When a parent element's connectedCallback() runs, its children may not have been created or connected yet if instantiated by the HTML parser.
.disconnectedCallback() runs when
- Removal: `element.remove()` or `parent.removeChild(element)`
- Replacement: `parent.replaceChild(newEl, oldEl)` or `parent.replaceChildren()`
- Wipes: `parent.innerHTML = ''` or `parent.textContent = ''`
Watch out:
this does not run on a hard page exit, you can try navigator.sendBeacon() or window.onbeforeunload = () => {}; / window.addEventListener("beforeunload", () => {});
Does not run when you never connect the element (.isConnected is false)
(Does not run when attached to a document.createDocumentFragment()) i never use these. Just watch out for offscreen stuff
- Reparenting/Moving: If an element is already in the DOM(!): `otherParent.appendChild(el)` fires `.disconnectedCallback()`, then fires `.connectedCallback()` on `el`
Watch out:
.moveBefore() will not run .disconnectedCallback() nor .connectedCallback()
disconnectedCallback is top down.
you need to mutateobserve all normal elements with added functionality
aChild.connectedCallback() {
// Defers execution until after the parser or parent append finishes
queueMicrotask(() => {
// Children and attributes are guaranteed to be present now!
this.initCanvasAndChildren();
});
}
more complex watch with MutationObserver for childList populated (but on every connected child, not just the last)
aParent.connectedCallback() {
if (this.children.length > 0) {
this.onReady();
} else {
const observer = new MutationObserver((mutations, obs) => {
obs.disconnect();
this.onReady();
});
observer.observe(this, { childList: true });
}
}
Easiest to catch dangling eventlisteners, fetches,
private abortController = new AbortController
const signal = this.abortController.signal;
this.canvas.addEventListener('pointermove', (e: PointerEvent) => this.editor.mousePositions.mouseScreen = [e.offsetX, e.offsetY], signal);
public deconstructor() {
this.abortController.abort();
}
Retrofit throttle is available, for loops try
function startLoop(signal: AbortSignal) {
function frame() {
if (signal.aborted) return; // Exit loop automatically!
render();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
V8 groups variables declared in the same lexical scope into a single shared Context object. TypeScript
function setup() { const hugeBuffer = new Float32Array(10_000_000); // 40MB const smallValue = 42;
// Listener A (dropped immediately):
const tempAction = () => { console.log(hugeBuffer[0]); };
// Listener B (attached to window for 1 hour):
window.addEventListener('click', () => { console.log(smallValue); });
}
You would think hugeBuffer gets collected because the click listener only uses smallValue. It does not. V8 creates one shared scope context for setup(). Because the click listener is alive, the entire shared context object (including hugeBuffer) is kept alive.
The Fix: Null out large temporary buffers (hugeBuffer = null) when setup completes.