← Back to patterns

Dynamic Import with Top-level Await Inside

Using {#await import()} to lazy load a component that uses top-level await

Pattern Usage:

<!-- Parent component -->
{#await import('../async-dataloader.svelte')}
  <p>Loading component...</p>
{:then { default: AsyncDataLoader }}
  <AsyncDataLoader />
{/await}

<!-- async-dataloader.svelte -->
<script>
  import { getDelayedTime } from './experimental.remote';
</script>

{#await getDelayedTime({ delay: 1000 })}
  <p>Loading data...</p>
{:then data}
  <p>{data.timestamp}</p>
{/await}

Live Demo:

Loading component dynamically...

How it works: Dynamic imports with {#await import()} let you lazy-load components. The imported component can use top-level await internally, creating a two-stage loading process: first the component loads, then its data loads. This is useful for code-splitting and reducing initial bundle size.