Performance: Common action patterns (click-outside, tooltip)
These patterns affect interaction responsiveness and visual stability by managing event listeners and DOM updates efficiently.
import { onMount, onDestroy } from 'svelte'; onMount(() => { const handleClick = event => { if (!element.contains(event.target)) { closeTooltip(); } }; window.addEventListener('click', handleClick); onDestroy(() => window.removeEventListener('click', handleClick)); });
window.addEventListener('click', (event) => { if (!element.contains(event.target)) { closeTooltip(); } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Global click listener without cleanup | Multiple listeners added | Multiple reflows on event | High paint cost on updates | [X] Bad |
| Global click listener with cleanup | Single listener active | Single reflow per event | Moderate paint cost | [OK] Good |
| Tooltip shown via JS reactivity | DOM nodes added/removed | Reflow and repaint on hover | Moderate paint cost | [!] OK |
| Tooltip shown via CSS hover | No DOM changes | No reflows on hover | Low paint cost | [OK] Good |
click-outside action pattern in Svelte?clickOutside action in a Svelte component?use: directive followed by the action name and optional parameters.use:clickOutside, which is the correct way to apply an action. Other options misuse event or binding syntax. <button use:tooltip={{ text: 'Save changes' }}>Save</button>tooltip action shows a small info box with the provided text when hovering or focusing the element.use:tooltip with text 'Save changes', so hovering triggers the tooltip display near the button. <script>
let open = true;
function close() { open = false; }
</script>
<div use:clickOutside={close} >
{#if open}
<p>Menu content</p>
{/if}
</div>use:clickOutside to work, the action must be imported or defined in the component.clickOutside, so the action won't run, preventing menu close.Pass the test and this pattern moves unknown