Svelte

svelte/window-events

Listen to window and document events with svelte:window and svelte:document, not addEventListener in $effect or onMount.

minorstaticfe-svelte

Why

A listener added by hand in onMount or $effect has to be removed by hand; forgetting the cleanup leaves handlers firing after the component is gone and doubles them when it comes back. The special elements add and remove the listener with the component and are safe in server rendering.

Fix

<svelte:window onkeydown={onKey} />, <svelte:document onvisibilitychange={sync} />, and bind:innerWidth, bind:scrollY or bind:online on <svelte:window> for the common values. For an element listener that needs options, use an attachment ({@attach}) that returns its cleanup.

Examples

<!-- bad -->
<script>
  import { onMount } from 'svelte'
  onMount(() => window.addEventListener('keydown', onKey))
</script>
<!-- good -->
<svelte:window onkeydown={onKey} />

Sources

Facts

Id
svelte/window-events
Severity
minor
Check
static checked in the source by audit
Applies to
svelte
Only in projects with
svelte sveltekit
Taught by the skill
fe-svelte Svelte components
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain svelte/window-events