Performance: Why events drive user interaction
This concept affects how quickly the page responds to user actions and how smoothly interactions feel.
function handleClick() { requestAnimationFrame(() => { console.log('Clicked'); }); } document.querySelectorAll('button').forEach(btn => { btn.addEventListener('click', handleClick); });
document.querySelectorAll('button').forEach(btn => { btn.addEventListener('click', () => { // heavy logic for(let i=0; i<1000000; i++) {} console.log('Clicked'); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous event handler | Minimal | Triggers 1 reflow if layout changes | High paint cost due to blocking | [X] Bad |
| Lightweight event handler with deferred work | Minimal | Single reflow if needed | Low paint cost, smooth interaction | [OK] Good |
on:click directive do?on:clickon:click directive in Svelte listens for when the user clicks on an element.on:eventName to listen to events, so on:submit is correct.<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Clicked {count} times</button>countlet are reactive, so updating count updates the UI.increment(), which adds 1 to count, updating the displayed text.<script>
let name = '';
function updateName(event) {
name = event.target.value;
}
</script>
<input type="text" on:input={updateName} />
<p>Hello, {name}!</p>on:input event fires whenever the user types, which is appropriate here.event.target.value correctly accesses the input's current value.shiftKey boolean indicating if Shift was pressed during the click.event.shiftKey before incrementing count, which is correct.count.shiftKey; { if(event.key === 'Shift') count++ }}>Click me checks event.key which is undefined on click events.Pass the test and this pattern moves unknown