Performance: Else and else-if blocks
This affects how the browser updates the DOM when conditionally rendering content, impacting interaction responsiveness and visual stability.
<script> let status = 'loading'; </script> {#if status === 'loading'} <p>Loading...</p> {:else if status === 'error'} <p>Error occurred.</p> {:else} <p>Data loaded.</p> {/if}
<script> let status = 'loading'; </script> {#if status === 'loading'} <p>Loading...</p> {/if} {#if status === 'error'} <p>Error occurred.</p> {/if} {#if status === 'success'} <p>Data loaded.</p> {/if}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate if blocks for mutually exclusive content | Multiple nodes created and destroyed | Up to 3 reflows per update | High paint cost due to multiple DOM changes | [X] Bad |
| Single if block with else-if and else | Only one node created/destroyed at a time | Single reflow per update | Lower paint cost with minimal DOM changes | [OK] Good |
{`\n{#if score >= 90}\n Excellent
\n{:else if score >= 60}\n Good
\n{:else}\n Try again
\n{/if}`}{`{#if isActive}\n Active
\n{:else if}\n Inactive
\n{/if}`}{`\n{#if status === 'loading'}\n Loading...
\n{:else if status === 'success'}\n Data loaded
\n{:else if status === 'error'}\n Error occurred
\n{:else}\n Idle
\n{/if}`}status is an empty string?Pass the test and this pattern moves unknown