Performance: Why load functions fetch data server-side
This affects the initial page load speed and reduces client-side JavaScript execution time by fetching data on the server before sending HTML to the browser.
export async function load({ fetch }) { const res = await fetch('/api/data'); const data = await res.json(); return { data }; } <script> export let data; </script> <p>{data.message}</p>
export async function load() { return { props: {} }; } <script> import { onMount } from 'svelte'; let data; onMount(async () => { const res = await fetch('/api/data'); data = await res.json(); }); </script> <p>{data ? data.message : 'Loading...'}</p>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side fetch in onMount | Extra DOM updates after load | Triggers 1 reflow per data update | Higher paint cost due to delayed content | [X] Bad |
| Server-side fetch in load function | DOM ready with data on first paint | Single reflow during initial layout | Lower paint cost, faster LCP | [OK] Good |
load functions fetch data on the server side before showing the page?load function in a SvelteKit page to fetch data server-side?load function in SvelteKit, what will the page receive as data?
export async function load() {
const res = await fetch('https://api.example.com/user');
const user = await res.json();
return { user };
}user.user property holding the parsed data, so the page receives this object.user property containing the fetched user data -> Option Aload function that tries to fetch data server-side:
export async function load() {
const response = fetch('/api/data');
const data = await response.json();
return { data };
}load functions to fetch data server-side and protect sensitive info?load runs on the server, so API keys and sensitive info stay hidden from users.load on the server, then pass it to the page; keep API keys secret on server -> Option BPass the test and this pattern moves unknown