0
0
Svelteframework~8 mins

HTML rendering with {@html} in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: HTML rendering with {@html}
MEDIUM IMPACT
This affects how quickly the browser can render dynamic HTML content and impacts layout stability and interaction responsiveness.
Rendering dynamic HTML content safely and efficiently
Svelte
<div>{#if safeHtml}<div>{@html safeHtml}</div>{/if}</div>
Conditionally rendering sanitized HTML reduces unexpected layout shifts and improves visual stability.
📈 Performance GainReduces reflows and CLS by controlling when HTML is injected
Rendering dynamic HTML content safely and efficiently
Svelte
<div>{@html dynamicHtml}</div>
Directly injecting raw HTML can cause layout shifts if content size changes after initial render and may introduce security risks if content is not sanitized.
📉 Performance CostTriggers multiple reflows if content size changes; can cause CLS issues
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Direct {@html} injection without controlInserts raw nodes dynamicallyMultiple reflows if content changesHigh paint cost due to layout shifts[X] Bad
Conditional rendering with sanitized HTMLControlled DOM insertionSingle or no reflows if stableLower paint cost with stable layout[OK] Good
Rendering Pipeline
When {@html} is used, the browser parses the injected HTML string and inserts it into the DOM, triggering style recalculation and layout if the content size changes.
DOM Construction
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout stage is most expensive due to reflows caused by dynamic content size changes.
Core Web Vital Affected
CLS
This affects how quickly the browser can render dynamic HTML content and impacts layout stability and interaction responsiveness.
Optimization Tips
1Avoid injecting large or frequently changing raw HTML with {@html} to reduce layout shifts.
2Sanitize and stabilize HTML content before using {@html} to improve visual stability.
3Use conditional rendering to control when {@html} content is inserted to minimize reflows.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance risk when using {@html} in Svelte?
AIncreasing JavaScript bundle size significantly
BBlocking network requests during rendering
CCausing layout shifts due to dynamic content size changes
DPreventing CSS from applying styles
DevTools: Performance
How to check: Record a performance profile while the component renders dynamic HTML with {@html}. Look for layout and paint events after HTML injection.
What to look for: Look for layout thrashing and long layout times indicating reflows; check for CLS warnings in the summary.