0
0
Svelteframework~8 mins

DOM event listeners (on:click) in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: DOM event listeners (on:click)
MEDIUM IMPACT
This affects interaction responsiveness and memory usage by managing how click events are handled in the browser.
Handling click events on many similar elements
Svelte
<script>
  let items = Array(1000).fill(0);
  function handleClick(event) {
    const index = event.target.dataset.index;
    if (index !== undefined) console.log(index);
  }
</script>
<div on:click={handleClick}>
  {#each items as item, i}
    <button data-index={i}>Click {i}</button>
  {/each}
</div>
Uses one listener on parent with event delegation, reducing memory and improving responsiveness.
📈 Performance GainSingle event listener instead of 1000, reducing memory and improving INP
Handling click events on many similar elements
Svelte
<script>
  let items = Array(1000).fill(0);
</script>
{#each items as item, i}
  <button on:click={() => console.log(i)}>Click {i}</button>
{/each}
Attaching 1000 separate click listeners causes high memory use and many event handlers to manage.
📉 Performance CostAdds 1000 event listeners, increasing memory and slowing interaction responsiveness
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Individual listeners per elementMany listeners attached (e.g., 1000)0 reflows triggered by listenersMinimal paint cost[X] Bad
Single delegated listener on parentOne listener attached0 reflows triggered by listenerMinimal paint cost[OK] Good
Rendering Pipeline
Click event listeners are registered during the DOM setup phase. When a click occurs, the browser triggers event dispatch, invoking the listener functions. Multiple listeners increase memory and event dispatch cost.
Event Registration
Event Dispatch
JavaScript Execution
⚠️ BottleneckEvent Dispatch and JavaScript Execution when many listeners exist
Core Web Vital Affected
INP
This affects interaction responsiveness and memory usage by managing how click events are handled in the browser.
Optimization Tips
1Avoid attaching separate event listeners to many similar elements.
2Use event delegation by attaching one listener to a common parent.
3Minimize JavaScript work inside event handlers for better responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with attaching a separate on:click listener to each of 1000 buttons?
ATriggers multiple reflows on each click
BHigh memory use and slower event dispatch due to many listeners
CIncreases paint cost significantly
DBlocks initial page load rendering
DevTools: Performance
How to check: Record a performance profile while clicking elements. Look for many event listener calls or long scripting times.
What to look for: High scripting time or many event listener calls indicates too many listeners; a single listener shows better performance.