Below is a complete example of an infinitely scrollable page built with Svelte 5. In this example, we simulate fetching more items from a server whenever the user scrolls near the bottom of the list. We use the Intersection Observer API to detect when a sentinel element at the bottom of our list becomes visible, then load the next batch of items.
You can create a file (for example, InfiniteScroll.svelte) and paste the following code:
<script>
import { onMount } from 'svelte';
// The list of items, current page, and loading flag
let items = [];
let currentPage = 0;
let loading = false;
let observer;
let sentinel; // reference to the sentinel element
// Simulate an async fetch for more items
async function fetchItems(page) {
// In a real app, replace this with a fetch() call to your API.
// Here, we simulate a network delay.
await new Promise((resolve) => setTimeout(resolve, 1000));
return Array.from({ length: 10 }, (_, i) => `Item ${page * 10 + i + 1}`);
}
// Load more items and update the list
async function loadMore() {
if (loading) return;
loading = true;
const newItems = await fetchItems(currentPage);
items = [...items, ...newItems];
currentPage++;
loading = false;
}
onMount(async () => {
// Load the initial set of items
await loadMore();
// Set up the intersection observer to load more when the sentinel is visible.
observer = new IntersectionObserver((entries) => {
// If the sentinel is in view, load more items.
if (entries[0].isIntersecting) {
loadMore();
}
});
if (sentinel) {
observer.observe(sentinel);
}
// Cleanup the observer when the component is destroyed.
return () => {
observer.disconnect();
};
});
</script>
<style>
.list {
display: flex;
flex-direction: column;
padding: 1rem;
}
.item {
border: 1px solid #ccc;
padding: 1rem;
margin-bottom: 0.5rem;
border-radius: 4px;
}
/* A small element for the observer */
.sentinel {
height: 1px;
}
.loading {
text-align: center;
padding: 1rem;
}
</style>
<div class="list">
{#each items as item}
<div class="item">{item}</div>
{/each}
</div>
<!-- This div acts as the trigger for loading more content. -->
<div bind:this={sentinel} class="sentinel"></div>
{#if loading}
<div class="loading">Loading more items…</div>
{/if}
How It Works
-
Script Section
- We maintain an array
items to store the list items, a currentPage counter, and a loading flag.
- The
fetchItems function simulates an asynchronous data fetch (in your project, you would replace this with a real API call).
- The
loadMore function checks if a load is already in progress, invokes fetchItems, and merges the new items with the existing list.
- The
onMount lifecycle hook initializes the list by loading the first batch of items and sets up an IntersectionObserver on the sentinel element. When the sentinel comes into view, loadMore is triggered.
-
Markup
- The component iterates over the
items array and displays each item.
- A
<div> with bind:this={sentinel} serves as the observation target. When the user scrolls and it becomes visible, more items are loaded.
- A conditional block displays a "Loading" message if the content is being loaded.
-
Style
- Basic styling is provided for a neat layout. Adjust or extend these styles as needed.
This example should run as-is in any Svelte 5 setup. Simply import and include the InfiniteScroll component in your application. Enjoy building your infinitely scrollable page!