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).
{#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.
{#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.
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.
- 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.