0
0
Svelteframework~8 mins

onMount in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: onMount
MEDIUM IMPACT
onMount affects the timing of when JavaScript code runs after the component is added to the page, impacting initial interaction readiness and rendering speed.
Running setup code when a component loads
Svelte
import { onMount } from 'svelte';
onMount(() => {
  setTimeout(() => {
    // heavy code deferred
    for (let i = 0; i < 100000000; i++) {}
  }, 0);
});
Defers heavy work to after initial rendering, keeping UI responsive.
📈 Performance GainImproves INP by avoiding main thread blocking during initial paint
Running setup code when a component loads
Svelte
import { onMount } from 'svelte';
onMount(() => {
  // heavy synchronous code
  for (let i = 0; i < 100000000; i++) {}
});
Heavy synchronous code inside onMount blocks the main thread, delaying user interaction readiness.
📉 Performance CostBlocks rendering and interaction for 100+ ms depending on device
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy synchronous code in onMount1 (component mount)1 reflow triggeredBlocks paint until done[X] Bad
Light or deferred code in onMount1 (component mount)1 reflow triggeredPaint happens promptly[OK] Good
Rendering Pipeline
onMount runs after the component is inserted into the DOM and after the browser paints. Heavy synchronous work here can delay input responsiveness.
JavaScript Execution
Layout
Paint
⚠️ BottleneckJavaScript Execution blocking main thread
Core Web Vital Affected
INP
onMount affects the timing of when JavaScript code runs after the component is added to the page, impacting initial interaction readiness and rendering speed.
Optimization Tips
1Keep onMount code light and fast to avoid blocking rendering.
2Defer heavy or long-running tasks asynchronously after mount.
3Use onMount only for setup that requires DOM access.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of running heavy synchronous code inside onMount?
AIt blocks the main thread, delaying user interaction readiness.
BIt increases the bundle size significantly.
CIt causes layout shifts after the page loads.
DIt prevents the component from mounting.
DevTools: Performance
How to check: Record a performance profile while loading the component. Look for long tasks during onMount execution.
What to look for: Long tasks blocking main thread after DOM insertion indicate slow onMount code.