Lazy Loading Svelte component

lazy loadsvelte

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

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}