Make your app resilient and responsive — svelte:boundary to contain crashes, lazy-loaded components for smaller pages, and a five-line portal for modals.
Why: a render error with no boundary can blank the entire app. <svelte:boundary> catches errors from everything inside it and shows the failed snippet instead, with reset to retry. Note: in a SvelteKit app, a +error.svelte file gives every route its own full-page error screen on top of this.
<script lang="ts">
import BrokenWidget from '$lib/components/BrokenWidget.svelte'
</script>
<!-- A crash inside stops here — the rest of the app keeps working -->
<svelte:boundary>
<BrokenWidget />
{#snippet failed(error, reset)}
<p>Something broke: {(error as Error).message}</p>
<button onclick={reset}>Try again</button>
{/snippet}
</svelte:boundary>Why: a heavy component the user might never see — a chart, an editor, a map — shouldn't be in the initial download. A dynamic import() fetches its code on demand, and {#await} renders it once it arrives. Smaller first page, same component.
<script lang="ts">
let showChart = $state(false)
// import() downloads the component's code only when called
const loadChart = () => import('$lib/components/HeavyChart.svelte')
</script>
<button onclick={() => (showChart = true)}>Show chart</button>
{#if showChart}
{#await loadChart() then { default: HeavyChart }}
<HeavyChart />
{:catch}
<p>Could not load the chart.</p>
{/await}
{/if}Why: modals, tooltips, and toasts break when a parent element clips its children (overflow: hidden) or layers them underneath other content (z-index). Svelte has no built-in portal, but an attachment — a function that receives the element — can move it to the end of <body> in five lines, while it still behaves like a normal child in your code.
<script lang="ts">
let open = $state(false)
// An attachment receives the real element once it exists
function portal(node: HTMLElement) {
document.body.appendChild(node) // move it to the end of <body>
return () => node.remove() // cleanup when the element leaves
}
</script>
<div style="overflow: hidden"> <!-- would clip a normal child -->
<button onclick={() => (open = true)}>Open modal</button>
{#if open}
<!-- Escapes overflow and z-index traps -->
<div {@attach portal} class="modal">
<p>I render into document.body</p>
<button onclick={() => (open = false)}>Close</button>
</div>
{/if}
</div>