Performance: Dimension bindings (clientWidth, clientHeight)
This affects page responsiveness and layout stability by triggering layout recalculations when reading element dimensions.
import { onMount } from 'svelte'; let width; let box; onMount(() => { width = box.clientWidth; window.addEventListener('resize', () => { width = box.clientWidth; }); }); // Use a reference and event listener to limit reads to resize events
let width; $: width = document.getElementById('box').clientWidth; // This runs on every reactive update, forcing layout thrashing
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reading clientWidth in reactive statement every update | Multiple DOM reads | Multiple reflows triggered | High paint cost due to layout thrashing | [X] Bad |
| Reading clientWidth on mount and resize event only | Few DOM reads | Single reflow per resize | Low paint cost, smooth rendering | [OK] Good |
bind:clientWidth do when used on an element?bind:clientWidth doesheight in Svelte?bind:property={variable} to connect element property to variable.bind:clientHeight={height} inside the element tag.<div> width is 300 pixels?<script>
let width = 0;
</script>
<div bind:clientWidth={width} style="width: 300px; height: 100px; background: lightblue;">Width: {width}px</div>width variablebind:clientWidth sets width to the element's actual width in pixels.width becomes 300.height:<script>
let height;
</script>
<section bind:clientHeight>Height: {height}px</section>bind:clientHeight={height}.bind:clientHeight is used without assigning it to height, so it won't update the variable.height variable to clientHeight. -> Option Abind:clientWidth. Which approach correctly implements this behavior?<script>
let width = 0;
</script>
<div bind:clientWidth={width} style="background: {width > 200 ? 'lightgreen' : 'lightcoral'}; width: 100%; height: 100px;">
Width: {width}px
</div> uses bind:clientWidth={width}, correctly binding width variable.<script>
let width = 0;
</script>
<div bind:clientWidth={width} style="background: {width > 200 ? 'lightgreen' : 'lightcoral'}; width: 100%; height: 100px;">
Width: {width}px
</div> uses a valid inline style with a ternary expression inside curly braces to change background color based on width.<script>
let width = 0;
</script>
<div style="background: {width > 200 ? 'lightgreen' : 'lightcoral'}; width: 100%; height: 100px;">
Width: {width}px
</div> lacks binding, so width stays 0. <script>
let width = 0;
</script>
<div bind:clientWidth style="background: {width > 200 ? 'lightgreen' : 'lightcoral'}; width: 100%; height: 100px;">
Width: {width}px
</div> misses variable in binding. <script>
let width = 0;
</script>
<div bind:clientWidth={width} style="background: width > 200 ? 'lightgreen' : 'lightcoral'; width: 100%; height: 100px;">
Width: {width}px
</div> uses invalid style syntax without curly braces around expression.Pass the test and this pattern moves unknown