# Svelte Performance Optimization Guide ## Overview Svelte is already highly performant by design, but there are patterns to ensure your applications stay fast as they grow. --- ## 📊 Understanding Svelte Reactivity ### How Svelte 5 Reactivity Works ```svelte ``` ### Avoid Unnecessary Reactivity ```svelte ``` --- ## 🚀 Component Optimization ### 1. Minimize Re-renders ```svelte {#each filteredItems as item (item.id)} {/each} ``` ### 2. Key Your Each Blocks ```svelte {#each items as item} {/each} {#each items as item (item.id)} {/each} {#each staticLabels as label, i (i)} {label} {/each} ``` ### 3. Lazy Load Components ```svelte {#if showChart} {#await loadChart() then Chart} {/await} {/if} ``` ### 4. Virtualization for Long Lists ```svelte ``` Simple Virtual List Implementation: ```svelte
scrollTop = e.currentTarget.scrollTop} >
{#each visibleItems as { item, index } (index)}
{@render children(item, index)}
{/each}
``` --- ## ⚡ Data Loading Optimization ### 1. Parallel Loading ```typescript // src/routes/dashboard/+page.ts import type { PageLoad } from './$types'; export const load: PageLoad = async ({ fetch }) => { // ✅ GOOD: Parallel fetching const [users, posts, stats] = await Promise.all([ fetch('/api/users').then(r => r.json()), fetch('/api/posts').then(r => r.json()), fetch('/api/stats').then(r => r.json()) ]); return { users, posts, stats }; }; // ❌ BAD: Sequential fetching export const loadBad: PageLoad = async ({ fetch }) => { const users = await fetch('/api/users').then(r => r.json()); const posts = await fetch('/api/posts').then(r => r.json()); const stats = await fetch('/api/stats').then(r => r.json()); return { users, posts, stats }; }; ``` ### 2. Streaming with Deferred Loading ```typescript // src/routes/dashboard/+page.server.ts import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ fetch }) => { // Critical data loads immediately const user = await fetch('/api/user').then(r => r.json()); // Non-critical data streams in return { user, // These are promises, will stream when ready posts: fetch('/api/posts').then(r => r.json()), recommendations: fetch('/api/recommendations').then(r => r.json()) }; }; ``` ```svelte

Welcome, {data.user.name}

{#await data.posts} {:then posts} {/await} {#await data.recommendations} {:then recommendations} {/await} ``` ### 3. Prefetching ```svelte About Products ``` --- ## 🖼️ Image Optimization ### Responsive Images ```svelte Hero image ``` ### Lazy Loading Images ```svelte
loaded = true} /> {#if !loaded}
{/if}
``` --- ## 🔄 Effect Optimization ### Debounce Effects ```svelte ``` ### Avoid Heavy Computations in Effects ```svelte ``` ### Cleanup Long-Running Effects ```svelte ``` --- ## 📦 Bundle Optimization ### Code Splitting ```typescript // vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [sveltekit()], build: { rollupOptions: { output: { manualChunks: { // Vendor chunks 'vendor-svelte': ['svelte'], 'vendor-chart': ['chart.js'], } } } } }); ``` ### Tree Shaking ```typescript // ✅ GOOD: Named imports enable tree shaking import { formatDate, formatCurrency } from '$lib/utils'; // ❌ BAD: Imports entire module import * as utils from '$lib/utils'; ``` ### Analyze Bundle ```bash # Install analyzer npm install -D rollup-plugin-visualizer # Add to vite.config.ts import { visualizer } from 'rollup-plugin-visualizer'; export default defineConfig({ plugins: [ sveltekit(), visualizer({ filename: 'stats.html', open: true }) ] }); ``` --- ## 📏 Measuring Performance ### Browser DevTools ```svelte ``` ### Core Web Vitals ```typescript // src/lib/vitals.ts import type { Metric } from 'web-vitals'; export function reportVitals(metric: Metric) { // Send to analytics console.log(metric.name, metric.value); // Or send to your analytics service fetch('/api/vitals', { method: 'POST', body: JSON.stringify(metric) }); } // In +layout.svelte import { onMount } from 'svelte'; import { reportVitals } from '$lib/vitals'; onMount(async () => { const { onCLS, onFID, onFCP, onLCP, onTTFB } = await import('web-vitals'); onCLS(reportVitals); onFID(reportVitals); onFCP(reportVitals); onLCP(reportVitals); onTTFB(reportVitals); }); ``` --- ## 📋 Performance Checklist ### Build Time - [ ] Minimal dependencies - [ ] Tree-shakeable imports - [ ] Code splitting configured - [ ] Image optimization ### Runtime - [ ] Keys on `{#each}` blocks - [ ] Virtualization for long lists - [ ] Debounced inputs - [ ] Lazy loaded heavy components - [ ] Optimized images (lazy, responsive) ### Data Loading - [ ] Parallel fetching where possible - [ ] Streaming for non-critical data - [ ] Prefetching for navigation - [ ] Caching strategies ### Effects - [ ] Cleanup functions for subscriptions - [ ] Debounced network requests - [ ] Heavy computations in `$derived` - [ ] AbortController for fetch