Performance: CSS-in-JS patterns with Svelte
This affects page load speed and rendering performance by controlling how styles are injected and updated in the DOM during component lifecycle.
<style>
.dynamic { color: red; }
</style>
<div class="dynamic">Hello</div><script> import { onMount } from 'svelte'; let styleElement; onMount(() => { styleElement = document.createElement('style'); styleElement.textContent = `.dynamic { color: red; }`; document.head.appendChild(styleElement); }); </script> <div class="dynamic">Hello</div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual style injection on mount | Adds style nodes dynamically | 1 reflow per component instance | Moderate paint delay | [X] Bad |
| Runtime CSS-in-JS library usage | Generates styles in JS | 1 reflow on mount | Blocks rendering until JS runs | [X] Bad |
| Svelte scoped styles (compiled) | Static style nodes | No runtime reflows | Fast paint | [OK] Good |
<script>
let color = 'blue';
</script>
<div style="color: {color};">Hello</div><script> let bg = 'yellow'; </script> <div style="background-color: bg;">Box</div>
isError. Which approach correctly applies CSS-in-JS to achieve this?<script>
export let isError = false;
</script>
<style>
.error { color: red; }
.normal { color: black; }
</style>
<p class="normal">Message</p> uses CSS classes but statically applies class='normal', ignoring the isError prop. <script> export let isError = false; </script> <p style="color: isError ? 'red' : 'black';">Message</p>misses curly braces around JS expression.
<script>
export let isError = false;
</script>
<p style="color: {isError ? 'red' : 'black'}">Message</p> correctly uses curly braces with a JS ternary expression inside style attribute. <script>
export let isError = false;
</script>
<style>
p { color: red; }
</style>
<p>Message</p> applies static red color always.Pass the test and this pattern moves unknown