-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Open
Description
Describe the bug
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:
- The element is detached from the DOM but still referenced in
last_propagated_event(an internal Svelte variable). - That element keeps its
onfocusandonblurlisteners. - Those listeners may hold references to any app objects — potentially large ones — causing unnecessary memory retention.
Reproduction
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>
Logs
System Info
System:
OS: Windows 10 10.0.19045
CPU: (16) x64 AMD Ryzen 7 PRO 6850U with Radeon Graphics
Memory: 13.33 GB / 30.77 GB
Binaries:
Node: 20.19.1 - E:\Program Files\nodejs\node.EXE
npm: 10.8.2 - E:\Program Files\nodejs\npm.CMD
pnpm: 10.18.3 - C:\Users\Mika\AppData\Roaming\npm\pnpm.CMD
Browsers:
Chrome: 143.0.7499.109
Edge: Chromium (125.0.2535.51)
Firefox: 144.0.2 - E:\Program Files\Mozilla Firefox\firefox.exe
Internet Explorer: 11.0.19041.3636
npmPackages:
rollup: 4.48.0 => 4.48.0
svelte: 5.46.0 => 5.46.0Severity
annoyance
Metadata
Metadata
Assignees
Labels
No labels