javascript / expert
Snippet
Non-Blocking Data Streaming in SvelteKit
Expert SvelteKit developers use data streaming to improve Time to First Byte (TTFB). By returning a promise without awaiting it in the load function, SvelteKit sends the initial HTML immediately. The client-side then resolves the promise and hydrates the specific component, preventing slow API calls from blocking the entire page render.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
// src/routes/+page.server.jsexport const load = async () => {const slowPromise = new Promise((resolve) => {setTimeout(() => resolve({ value: 'Delayed Data' }), 3000);});return {immediate: 'Available instantly',streamed: slowPromise};};
svelte
Breakdown
1
const slowPromise = ...
Create a promise that represents a long-running operation like a database query.
2
return { ... streamed: slowPromise }
Returning the promise directly (un-awaited) triggers SvelteKit's streaming mechanism.