0
0
Tailwindmarkup~8 mins

Dark mode toggle with JavaScript in Tailwind - Performance & Optimization

Choose your learning style9 modes available
Performance: Dark mode toggle with JavaScript
MEDIUM IMPACT
This affects page interactivity and visual stability when toggling themes.
Implementing a dark mode toggle that switches the page theme
Tailwind
const toggleDarkMode = () => {
  document.documentElement.classList.toggle('dark');
};

button.addEventListener('click', toggleDarkMode);
Toggling a single class leverages CSS for style changes, causing only one reflow and repaint, improving responsiveness and visual stability.
📈 Performance GainSingle reflow and repaint, reduces layout thrashing, improves CLS and INP metrics.
Implementing a dark mode toggle that switches the page theme
Tailwind
const toggleDarkMode = () => {
  document.body.style.backgroundColor = '#000';
  document.body.style.color = '#fff';
};

button.addEventListener('click', toggleDarkMode);
Directly changing many inline styles triggers multiple reflows and repaints, causing layout thrashing and slower interaction.
📉 Performance CostTriggers multiple reflows and repaints per style change, blocking rendering for 50-100ms on complex pages.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Inline style changes per propertyMultiple style updates on bodyMultiple reflows triggeredHigh paint cost due to many changes[X] Bad
Toggle single CSS class on rootOne class toggle on <html>Single reflow triggeredMinimal paint cost[OK] Good
Rendering Pipeline
When toggling dark mode by adding/removing a class, the browser recalculates styles, performs layout if needed, repaints affected areas, and composites the final pixels.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint stages are most expensive if many inline styles change individually.
Core Web Vital Affected
CLS
This affects page interactivity and visual stability when toggling themes.
Optimization Tips
1Toggle a single CSS class on the root element to switch themes.
2Avoid changing multiple inline styles individually to prevent layout thrashing.
3Use DevTools Performance tab to monitor style recalculations and layout events.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of toggling a CSS class for dark mode instead of changing inline styles directly?
AIt triggers fewer reflows and repaints
BIt increases the bundle size
CIt blocks the main thread longer
DIt causes more layout thrashing
DevTools: Performance
How to check: Open DevTools > Performance tab. Record while toggling dark mode. Look for style recalculation, layout, and paint events.
What to look for: Check if style recalculation and layout happen once per toggle. Multiple layout events indicate inefficient style changes.