Performance: Transition directive (transition:fade)
This affects the rendering performance during element appearance and disappearance by animating opacity changes smoothly.
<script> import { fade } from 'svelte/transition'; let visible = false; </script> <button on:click={() => visible = !visible}>Toggle</button> {#if visible} <div transition:fade>Content fades in and out</div> {/if}
<div style="opacity: 0; transition: opacity 0.5s;" bind:this={el}></div> <script> // Manually toggling opacity with JS function show() { el.style.opacity = '1'; } function hide() { el.style.opacity = '0'; } </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual opacity toggle with JS | Multiple style changes | Multiple reflows per toggle | High paint cost due to layout thrashing | [X] Bad |
| Svelte transition:fade directive | Minimal DOM ops | No reflows triggered | Low paint cost, GPU accelerated | [OK] Good |
transition:fade directive do in Svelte?transition:fade<div transition:fade={{ duration: 500 }}></div> uses correct syntax: { duration: 500 }. The option with {{duration=500}} uses = instead of :, the option with duration: '500' uses quotes around the number, and the option with duration: 500ms adds invalid 'ms' unit.<script>
let visible = true;
</script>
<button on:click={() => visible = !visible}>Toggle</button>
{#if visible}
<div transition:fade>Hello</div>
{/if}visible variable, which controls if the <div> is shown or hidden. The transition:fade applies a fade animation on enter and leave.<p transition:fade duration=300>Hello</p>
transition:fade duration=300 which is invalid syntax. Options must be passed as an object inside curly braces.transition:fade={{ duration: 300 }} with double curly braces and colon.transition:fade. Which approach correctly applies this in Svelte?{#each items as item, i}<li transition:fade={{ delay: i * 200 }}>{item}</li>{/each} uses the index i to multiply delay, correctly staggering fades. Use {#each items as item}<li transition:fade={{ delay: 200 }}>{item}</li>{/each} without index uses fixed delay, so all fade together. Use {#each items as item}<li transition:fade={{ duration: i * 200 }}>{item}</li>{/each} with duration instead of delay incorrectly uses duration for delay. Use {#each items as item}<li transition:fade={{ delay: 200 * items.length }}>{item}</li>{/each} same delay for all applies same delay to all.Pass the test and this pattern moves unknown