Performance: Inline event handlers
This affects interaction responsiveness and page load speed by how event listeners are attached and managed.
<script> function handleClick() { /* logic */ } </script> <button on:click={handleClick}>Click me</button>
<button onclick="handleClick()">Click me</button>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline event handler attribute | Multiple event listener re-registrations | 0 | Low | [X] Bad |
| Svelte on:click binding | Single event listener per element | 0 | Low | [OK] Good |
handleClick inline in a Svelte component?on:eventName={handler} to attach event handlers inline.<button on:click={handleClick}>Click me</button> correctly uses on:click={handleClick}, which is the Svelte pattern.keydown event inline in Svelte?on: prefix before event names for inline handlers.<input on:keydown={handleKeydown} /> uses on:keydown={handleKeydown}, which is the correct Svelte syntax.<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Clicked {count} times</button>increment function increases count by 1 on each click.{count} value when count changes.<script>
function sayHi() {
alert('Hi!');
}
</script>
<button on:click=sayHi>Say Hi</button>on:click={sayHi}.on:click=sayHi without braces, which is invalid syntax.<button on:click={incrementIfShift}>Increment</button>
<script>
let count = 0;
function incrementIfShift(event) {
if (event.shiftKey) count += 1;
}
</script> correctly defines incrementIfShift(event) and checks event.shiftKey. <button on:click={incrementIfShift}>Increment</button>
<script>
let count = 0;
function incrementIfShift() {
if (event.shiftKey) count += 1;
}
</script> misses the event parameter. <button on:click={event => { if(event.shiftKey) count += 1 }}>Increment</button> uses inline arrow function correctly but does not declare count in snippet. <button on:click={event => { if(event.key === 'Shift') count++ }}>Increment</button> incorrectly checks event.key on click event.Pass the test and this pattern moves unknown