Performance: svelte:body for body events
This affects how event listeners on the entire page body impact interaction responsiveness and memory usage.
<script> function handleKeydown(event) { console.log(event.key); } </script> <svelte:body on:keydown={handleKeydown} />
<script> function handleKeydown(event) { console.log(event.key); } </script> <div on:keydown={handleKeydown} tabindex="0"> Focus me and press keys </div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Local element event listener | Few nodes affected | 0 reflows | Minimal paint | [!] OK |
| svelte:body global event listener | Single global listener | 0 reflows | Minimal paint | [OK] Good |
svelte:body in a Svelte component?svelte:bodysvelte:body is a special tag in Svelte that allows you to listen to events on the whole page's body element.svelte:body does not do.svelte:body?svelte:body is used to listen to events on the body element. The syntax is <svelte:body on:event={handler} />.<svelte:body on:click={handleClick} /> uses <svelte:body on:click={handleClick} />, which is correct. <body on:click={handleClick}></body> tries to add event on a normal body tag inside component, which is invalid. <div on:bodyclick={handleClick}></div> uses a non-existent event bodyclick. <svelte:window on:click={handleClick} /> listens on svelte:window, not svelte:body.<script>
function handleKey(event) {
console.log(event.key);
}
</script>
<svelte:body on:keydown={handleKey} />svelte:body tag listens to events on the page's body. Here, it listens for keydown events and calls handleKey.handleKey logs event.key, which is the name of the key pressed (like 'a', 'Enter').<script>
function clickHandler() {
alert('Body clicked');
}
</script>
<svelte:body onclick={clickHandler} />on:eventName, for example on:click. Using onclick is invalid.svelte:body supports click events, and alert is allowed in handlers.svelte:body is best to achieve this behavior?<svelte:body on:click={handleClickOutside} /> and check if the click target is outside the dropdown element. uses svelte:body to listen globally and then checks if the click target is outside the dropdown, which is the correct approach. Add on:click directly on the dropdown element only. only listens on the dropdown itself, so clicks outside won't be detected. Use <svelte:window on:click={closeDropdown} /> without checking the click target. listens on window but doesn't check target, so it closes even when clicking inside. Listen for click events on a parent div wrapping the dropdown. listens on a parent div, which may not cover the whole page.Pass the test and this pattern moves unknown