Once you add real-time features, the first paint can slow down. This chapter covers how to load only what you need, when you need it.
Key terms
- Code splitting: breaking the bundle into chunks so each route downloads only what it needs.
- Prefetch: detecting soon-to-be-clicked links and fetching their code or data ahead of time.
- Lazy loading: delaying heavy components or images until they are actually required.
browservariable: SvelteKit's flag that tells you whether the current code is running in the browser, useful for gating client-only components.
Core ideas
Code splitting shrinks initial bundles by loading route-specific chunks on demand. Prefetch grabs assets before the user clicks, hiding network latency. Lazy loading keeps expensive UI out of the initial render so the first interaction feels fast.
Important SvelteKit performance guidelines
import()only splits bundles when it runs in the browser. Dynamic imports in server-only files stay in the main chunk, so call them inside.sveltecomponents.sveltekit:prefetchworks only on<a>elements. Convert buttons to links or callprefetchRoutesin an interaction handler.- The
browservariable comes from$app/environment. Import it explicitly; otherwise you'll hit aReferenceError.
Code examples
Here is a combined example of dynamic imports plus link prefetching.
<script>
let AdminPanelPromise;
async function loadAdminPanel() {
AdminPanelPromise = import('$lib/components/AdminPanel.svelte');
}
</script>
{#if AdminPanelPromise}
{#await AdminPanelPromise}
<p>Loading the admin UI…</p>
{:then Module}
<Module.default />
{/await}
{:else}
<button on:click={loadAdminPanel}>Open admin tools</button>
{/if}
<a sveltekit:prefetch href="/reports">Reports</a>
The admin panel loads on demand, and the Reports link prepares its chunk as soon as it enters the viewport.
Lazy load visual assets such as charts or hero images.
{#if browser}
<LazyChart {data} />
{:else}
<ChartSkeleton />
{/if}
<picture>
<source srcset={heroWebp} type="image/webp" />
<img src={heroJpg} alt="Learning progress" loading="lazy" decoding="async" />
</picture>
Why it matters
School networks often fluctuate. When the initial view remains light, users stay engaged even under bad bandwidth. Code splitting and prefetch act as seatbelts, ensuring the critical screen appears first.
Practice
- Try it: add the dynamic import button plus a
sveltekit:prefetchlink, then inspect the network panel. - Extend it: apply
loading="lazy"to images or guard a chart component behind thebrowserflag. - Debug it: if the bundle stays large, review the
import()path and route group structure. - Definition of done: the admin panel downloads only on request, and prefetched links show data instantly.
Wrap-up
Performance improvements compound. Next you will prepare for production with deployment flows and environment variables.
💬 댓글
이 글에 대한 의견을 남겨주세요