Performance: Using data in pages
This affects how quickly the page loads and updates by controlling data fetching and rendering timing.
<script context="module"> export async function load() { const res = await fetch('/api/data'); const data = await res.json(); return { props: { data } }; } </script> <script> export let data; </script> <p>{data.message}</p>
<script>
let data;
fetch('/api/data')
.then(res => res.json())
.then(json => data = json);
</script>
{#if data}
<p>{data.message}</p>
{/if}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetch data inside component after render | Minimal initially, but triggers updates | Triggers 1 reflow per data update | Multiple paints as data arrives | [X] Bad |
| Fetch data in load function before render | DOM built with data ready | Single layout and paint | Single paint with stable content | [OK] Good |
| Load minimal data first, fetch large data lazily | Initial DOM small, updates later | 1 reflow when large data arrives | Initial paint fast, later paint deferred | [!] OK |
{} to insert JavaScript expressions or variables into HTML.{variable} inside HTML shows the variable's value dynamically.{variable} inside the HTML. -> Option B<script> block?<script>, so let is the preferred way to declare variables that can change.let name = 'Svelte'; correctly declares a variable with a string value.let name = 'Svelte'; -> Option C<script>
let fruits = ['Apple', 'Banana', 'Cherry'];
</script>
<ul>
{#each fruits as fruit}
<li>{fruit}</li>
{/each}
</ul>fruits and creates an <li> for each item.<li>, so the output is a list with three items.<script>
let count = 0
</script>
<button on:click={count++}>Click me</button>
<p>Clicked {count} times</p>count++ inside on:click is valid and works as an event handler that increments count.count and displays the updated value.const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Carol', age: 35 }
];<div> using {#each}?{#each users as user, index} correctly loops over users and provides both user object and index.{user.name} and {user.age} correctly access properties. Including index shows user number.{#each users as user, index}
<div>User {index}: {user.name} ({user.age})</div>
{/each} [OK]Pass the test and this pattern moves unknown