Skip to content

Instantly share code, notes, and snippets.

@furic
Last active July 28, 2025 02:17
Show Gist options
  • Save furic/9fcafa34d426998640fb936faf94cd9a to your computer and use it in GitHub Desktop.
Save furic/9fcafa34d426998640fb936faf94cd9a to your computer and use it in GitHub Desktop.

Svelte Lazy Loading Components: Svelte 4 vs Svelte 5 (Runes)

Description

This gist demonstrates how to lazy load Svelte components using dynamic imports, comparing the syntax between Svelte 4 and Svelte 5 (runes mode). Lazy loading is a powerful technique to optimize bundle size and improve performance by loading components only when needed (e.g., widgets, modals, or rarely-used UI).


Svelte 4 Syntax

{#await import('./MyWidget.svelte') then Widget}
  <svelte:component this={Widget.default} someProp={value} />
{/await}
  • Uses <svelte:component> for dynamic rendering.
  • Props are passed as usual.

Svelte 5 (Runes) Syntax

{#await import('./MyWidget.svelte') then Widget}
  <Widget.default someProp={value} />
{/await}
  • Directly uses the imported component as a tag.
  • This is the idiomatic way for lazy loading in Svelte 5.
  • Direct invocation (Widget.default({ someProp: value })) is for advanced use cases, not markup.

Dynamic Import in a Loop

You can dynamically load a component inside an {#each} loop:

{#each items as item}
  {#await import('./MyWidget.svelte') then Widget}
    <Widget.default data={item} />
  {/await}
{/each}

Performance Note:

  • Svelte will only import the module once, even if the loop has many items. Subsequent imports use the cached module, so there is no repeated network or disk load.
  • The only overhead is rendering multiple component instances, which is normal for any list rendering.

Why & Benefits

  • Performance: Reduces initial bundle size by loading code only when needed.
  • User Experience: Faster initial load, especially on mobile.
  • Scalability: Keeps your app maintainable and modular.

References


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment