I couldn't find any working solution for this online, so I thought to share it when I got it to work.
I needed a maintenance page that would take over the entire site when enabled, but loading it on every page visit seemed wasteful. The component should only load when actually needed.
The {#await} block in Svelte lets you handle promises right in your template. Pair that with dynamic import() for lazy-loading, and you've got yourself a concise and clear way to handle async components.
Here's the code:
<script> // info.maintenance (boolean) && info.maintenance_ends (timestamp) export let info; const MaintenanceComponent = info?.maintenance ? import("$lib/components/Maintenance.svelte") : null; </script> {#if MaintenanceComponent} {#await MaintenanceComponent then M} {@const Maintenance = M.default} <Maintenance time={info.maintenance_ends} /> {:catch error} <p>Failed to load maintenance page: {error.message}</p> {/await} {/if}
Pro tip: Keep async operations out of $effect runes – they don't play well together, and TypeScript will let you know about it.
Happy Hacking!
The above is the detailed content of A short guide to Async Components in Svelte 5. For more information, please follow other related articles on the PHP Chinese website!