DEV Community

Abdullah Bashir
Abdullah Bashir

Posted on • Edited on

3 1 1 1 1

A short guide to Async Components in Svelte 5

I couldn't find any working solution for this online, so I thought to share it when I got it to work.

The Problem: Asynchronous Components

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 Solution: Combining {#await} with Dynamic Imports

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}
Enter fullscreen mode Exit fullscreen mode
  • Dynamic Import: I used import() to load the Maintenance.svelte component asynchronously. This makes sure the component is only loaded when maintenance mode is turned on.
  • {#await} Block: This block allows me to await the import.
  • {@const}: The {@const}block allows you to extract the default export (M.default) into a local variable.

Happy Hacking!

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay