Svelte Lazy Component is a library designed for dynamically loading components in your Svelte project. It supports asynchronous component loading, passing dynamic props, and handling events effortlessly.
import()
to load components asynchronously.Use LazyComponent
to load components dynamically.
<script>
import LazyComponent from '$lib/LazyComponent.svelte';
let inputValue = '';
</script>
<LazyComponent
component={() => import('$components/Input.svelte')}
defaultValue="Lazy Loaded Value"
onInput={(event) => {
inputValue = event.target.value;
}}
/>
<p>Input Value: {inputValue}</p>
You can pass props and add child content.
<LazyComponent
component={() => import('$components/Hello.svelte')}
name="John Doe"
>
<p>This is child content</p>
</LazyComponent>
Use #each
to render multiple LazyComponent
instances.
<script>
const avatars = Array.from({ length: 5 }, (_, i) => ({
url: `https://picsum.photos/200/200?id=${i}`,
name: `User ${i}`,
content: `Content ${i}`,
}));
</script>
{#each avatars as avatar}
<LazyComponent
component={() => import('$components/GalleryPhoto.svelte')}
{...avatar}
/>
{/each}
component
(required): An asynchronous function to load the component (import()
)....props
: Properties passed to the loaded component.on:eventName
).Check out the implementation example on GitHub Repository.
We welcome contributions to this project! Here's how you can help:
This library is released under the MIT License. Feel free to use it in your projects.
Contributions are highly appreciated! Let's make this library even better. 🚀