Memory leak due to unsubscribed event listeners in Svelte's internal handling.
The issue describes a memory leak where certain event listeners (onfocus, onblur) are not properly unsubscribed when elements are detached from the DOM, potentially retaining large objects in memory. The fix would require modifying Svelte's internal event handling logic, but the exact scope across versions (Svelte 4 vs 5) needs verification. The reproduction case is clear but the solution might touch core event propagation logic.
At least the onfocus and onblur event listeners are not being unsubscribed.
Other listeners I haven’t checked.
onclick listeners are properly cleaned up on Svelte 5, but not on Svelte 4
Here’s how the memory leak happens in my case:
last_propagated_event (an internal Svelte variable).onfocus and onblur listeners.Svelte 5: https://svelte.dev/playground/127c05413cf1475998aa0fcefa2ab10f?version=5.46.0 Svelte 4: https://svelte.dev/playground/7fb7862b534a44009161bdf28de1d3a2?version=5.46.0
<script>
let visible = $state(true);
let elems = []
if (typeof window !== 'undefined') {
window.elems = elems
}
let elem = $state(null);
$effect(() => {
if (elem != null) {
elems.push(elem)
}
console.log(elem)
})
function onClick() {
console.log('click')
}
function onFocus() {
console.log('focus')
}
function onBlur() {
console.log('blur')
}
</script>
<button onclick={() => visible = !visible}>Show/Hide</button>
<br>
<br>
{#if visible}
Test Element:
<input
type="radio"
bind:this={elem}
onclick={onClick}
onfocus={onFocus}
onblur={onBlur}
/>
{/if}
<div>
<br>
1) Click on the Show/Hide many times
<br>
2) Run this code in dev tools to see remaining events listeners:
<br>
<code>
elems.map(o => getEventListeners(o))
</code>
<br>
3) onclick was unsubscribed but onfocus/onblur stil there
<br>
* If an element becomes Detached but is still retained in memory for various reasons, this leads to retention of not only the listeners but also all objects held by these functions, which can lead to large memory leaks
</div>
System:
OS: Windows 10 10.0.19045
CPU: (16) x64 AMD Ryzen 7 PRO 6850U with Radeon Gr
Claim this issue to let others know you're working on it. You'll earn 10 points when you complete it!