Lazy wrapper for Svelte components inspired by React.lazy().
Only supports Svelte 5 components.
npm i -D svelte-lazy-components
These utilities expect a function that returns a Promise
with the component to be loaded as the default
export.
lazy()
returns a regular Svelte component, that will load the component upon first render.
import { lazy } from 'svelte-lazy-components';
const LazyComponent = lazy(() => import('./LazyComponent.svelte'));
In your Svelte components:
<script>
import { lazy, Lazy } from 'svelte-lazy-components';
const LazyComponent = lazy(() => import('./LazyComponent.svelte'));
</script>
<LazyComponent name="World!" />
<!-- or with Lazy -->
<Lazy provider={() => import('./LazyComponent.svelte')} props={{name: 'World'}} />
You can also use fallback
prop to show a loading component while the lazy component is loading:
<script>
import { Lazy } from 'svelte-lazy-components';
import Loading from './Loading.svelte';
</script>
<Lazy provider={() => import('./LazyComponent.svelte')} props={{name: 'World!'}}>
{#snippet fallback()}
<p>Loading...</p>
{/snippet}
</Lazy>
<script>
import { lazy } from 'svelte-lazy-components';
let condition = $state(false);
// HeavyComponent.svelte will be loaded only when condition is true
const HeavyComponent = lazy(() => import('./HeavyComponent.svelte'));
</script>
{#if condition}
<HeavyComponent name="World!" />
{/if}
You can use lazy()
to load components from a library only when they are needed:
import { lazy } from 'svelte-lazy-components';
const mappedComponents = {
ComponentA: lazy(() => import('my-library/ComponentA.svelte')),
ComponentB: lazy(() => import('my-library/ComponentB.svelte')),
};
You can use lazy()
to load different components based on some condition:
<script>
import { lazy } from 'svelte-lazy-components';
const isFeatureEnabled = Math.random() > 0.5;
const LazyComponent = lazy(() => {
if (isFeatureEnabled) {
return import('./ComponentA.svelte');
} else {
return import('./ComponentB.svelte');
}
});
</script>
<LazyComponent />
or
<script>
import { lazy } from 'svelte-lazy-components';
const isFeatureEnabled = Math.random() > 0.5;
const ComponentA = lazy(() => import('./ComponentA.svelte'));
const ComponentB = lazy(() => import('./ComponentB.svelte'));
</script>
{#if isFeatureEnabled}
<ComponentA />
{:else}
<ComponentB />
{/if}
Apache-2.0