Performance: Page load functions (+page.js)
This affects the initial page load speed by controlling data fetching before the page renders.
export async function load({ fetch }) { const res = await fetch('https://api.example.com/summary-data'); const data = await res.json(); return { data }; }
export async function load() { const res = await fetch('https://api.example.com/large-data'); const data = await res.json(); return { data }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sequential fetch in +page.js | Minimal DOM changes | 1 reflow after data arrives | Paint delayed by data fetch | [X] Bad |
| Parallel fetch with Promise.all | Minimal DOM changes | 1 reflow after data arrives | Paint happens sooner | [OK] Good |
load function in a +page.js file in SvelteKit?load in SvelteKitload function runs before the page renders to get data or do setup.load function in +page.js?load is exported as a named export, usually a const arrow function returning data without wrapping in props.load as a named const returning an object with data directly, which is correct. export function load() { return { props: { message: 'Hi' } }; } wrongly uses props key, function load() { return { message: 'Hi' }; } lacks export, export default function load() { return { props: { message: 'Hi' } }; } uses default export which is incorrect.+page.js code, what will be the value of data.greeting inside the page component?export const load = () => {
return { greeting: 'Hello, Svelte!' };
};greeting and value 'Hello, Svelte!'.data object in the page component. So data.greeting equals 'Hello, Svelte!'.+page.js load function:export const load = async () => {
const res = await fetch('/api/data');
const data = await res.json();
return data;
};return { data }, so the page receives it properly.+page.js load function. Which code snippet correctly does this?redirect function from '@sveltejs/kit' which throws an exception to redirect the user.redirect and throws it when user is not authenticated. export const load = () => {
const user = null;
if (!user) return '/login';
return { user };
}; returns a string which is invalid. export const load = () => {
const user = null;
if (!user) window.location.href = '/login';
return { user };
}; uses browser redirect which won't work server-side. import { redirect } from '@sveltejs/kit';
export const load = () => {
const user = null;
if (!user) return redirect(302, '/login');
return { user };
}; returns redirect instead of throwing it, which is incorrect.Pass the test and this pattern moves unknown