Performance: Flip animations
Flip animations impact the smoothness of visual transitions and the responsiveness of user interactions during element position changes.
import { flip } from 'svelte/animate'; <ul> {#each items as item (item.id)} <li animate:flip>{item.name}</li> {/each} </ul>
let items = [...]; // On reorder, directly change element styles like top/left // or manipulate DOM causing layout recalculations function reorder() { items = reorderedItems; // no animation or use top/left changes triggering layout }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct top/left animation | High (style changes trigger layout) | Multiple per frame | High (layout + paint) | [X] Bad |
| Svelte flip animation (transform) | Low (no layout changes) | Zero during animation | Low (composite only) | [OK] Good |
animate:flip in Svelte?animate:flip doesanimate:flip without parentheses or other modifiers on elements. <script>
let items = [1, 2, 3];
function shuffle() {
items = items.sort(() => Math.random() - 0.5);
}
</script>
<ul animate:flip>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
<button on:click={shuffle}>Shuffle</button><script>
let items = ["a", "b", "c"];
</script>
<ul animate:flip>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
<button on:click={() => items.push("d")}>Add D</button>items.push("d") mutates the array but does not update the variable reference, so Svelte won't detect change.items, the list won't update or animate.<script>
let items = ["x", "y", "z"];
function addItem() {
items = [...items, "new"];
}
function removeItem() {
items = items.slice(1);
}
function shuffle() {
items = items.sort(() => Math.random() - 0.5);
}
</script>
<ul animate:flip>
{#each items as item (item)}
<li>{item}</li>
{/each}
</ul>
<button on:click={addItem}>Add</button>
<button on:click={removeItem}>Remove</button>
<button on:click={shuffle}>Shuffle</button>(item) important here?Pass the test and this pattern moves unknown