Lazy Loading Svelte component
<script> let lazyComponent; function load() { lazyComponent = import(`./LazyComponent.svelte`); } let count = 0;</script>{#if lazyComponent} {#await lazyComponent then { default: LazyComponent }} <LazyComponent {count} /> {/await}{/if}<button on:click={load}>Load</button><button on:click={() => count ++}>Increment</button>
<!-- LazyComponent.svelte --><script> export let count;</script><strong>{count}</strong>
Notes
- For rollup users, dynamic imports only supported in the following output formats:
- esm
- amd
- systemjs
Dynamic Lazy Component
This is great! I tried turning lazy loading into its own component, but got burned by dynamic imports of variables. Any thoughts on how this could work? pic.twitter.com/yCDadJYFqf
— sean mullen (@srmullen) August 12, 2020
You can't use dynamic expressions for import()
in rollup.
A better approach for dynamic lazy component would be passing in a function that will return a dynamic component
<script> import LazyComponent from './LazyComponent.svelte'; let load = false;</script><LazyComponent when={load} component={() => import('./LoadMeLikeLazy.svelte')} /><button on:click={() => { load = true; }}>Load</button>
<!-- filename: LazyComponent.svelte --><script> export let when = false; export let component; let loading; $: if (when) { load(); } function load() { loading = component(); }</script>{#if when} {#await loading then { default: Component }} <Component /> {/await}{/if}