CSS Memory Leak Investigation Playbook
This playbook provides a systematic approach to diagnosing CSS-related memory leaks in web applications. CSS leaks often stem from:
- Persistent animations/transitions holding DOM references.
- CSS-in-JS libraries generating unbound stylesheets/rules.
- Cloned/detached DOM nodes retaining computed styles.
- Infinite style recalculations or observer-driven style injections.
Key Tools:
- PerformanceObserver: Monitors performance entries (e.g., LongTask, PaintTiming) to correlate leaks with jank/paint stalls.
- MutationObserver: Detects DOM mutations involving styles (e.g.,
<style> insertions, class/attribute changes).
- Custom Heuristics: JS-based metrics like CSS rule counts, animation tracking, and heap growth detection.
Prerequisites:
- Chrome/Edge DevTools (best Memory tab support).
- Open DevTools > Console.
- Enable Performance > Memory checkbox for heap snapshots.
- Test on a page exhibiting leaks (e.g., after navigation, component unmount, or load/unload cycles).
- Paste code snippets directly into Console.
Safety Note: Run in a test environment. These scripts log aggressively—filter by [CSS-LEAK] in Console.
Phase 1: Baseline Measurement
Establish memory/performance baseline before suspected leak trigger.
-
Record Initial Heap Snapshot:
code
const takeSnapshot = (label) => chrome && chrome.debugger ? console.log('Use DevTools Memory tab: Heap snapshot') : performance.memory && console.table({[label]: performance.memory});
takeSnapshot('baseline');
-
Start PerformanceObserver for LongTasks/Paints:
js
const perfObserver = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.entryType === 'longtask' || entry.entryType === 'paint') {
console.log(`[CSS-LEAK] ${entry.entryType}:`, entry.duration, 'ms at', entry.startTime);
}
});
});
perfObserver.observe({entryTypes: ['longtask', 'paint', 'mark']});
console.log('[CSS-LEAK] PerfObserver started');
- Triggers: LongTasks (>50ms) often signal rec-style thrashing.
-
Poll Memory Usage (Chrome-only via performance.memory):
js
let memSamples = [];
const memInterval = setInterval(() => {
if (performance.memory) {
const mem = performance.memory.usedJSHeapSize / 1024 / 1024; // MB
memSamples.push(mem);
console.log(`[CSS-LEAK] Heap: ${mem.toFixed(1)}MB`);
if (memSamples.length > 10 && memSamples.slice(-1)[0] - memSamples[0] > 10) {
console.warn('[CSS-LEAK] Potential growth detected:', memSamples.slice(-1)[0] - memSamples[0]);
}
}
}, 1000);
Phase 2: MutationObserver for Style Changes
Monitor DOM mutations that could leak styles (e.g., dynamic <style>, class flips).
js
const styleMutations = [];
const mutationObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
let styleRelated = false;
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(node => {
if (node.nodeName === 'STYLE' || node.nodeName === 'LINK') styleRelated = true;
});
mutation.removedNodes.forEach(node => {
if (node.nodeName === 'STYLE' || node.nodeName === 'LINK') styleRelated = true;
});
} else if (mutation.type === 'attributes' && (mutation.attributeName === 'class' || mutation.attributeName === 'style')) {
styleRelated = true;
}
if (styleRelated) {
console.log('[CSS-LEAK] Style mutation:', mutation);
styleMutations.push(mutation);
}
});
});
mutationObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'style']
});
console.log('[CSS-LEAK] MutationObserver started');
- Action: Trigger leak (e.g., navigate SPA route, unmount component). Watch for excessive
<style> adds/removes without cleanup.
Phase 3: Custom Heuristics
Inject these functions to quantify CSS bloat.
-
Track CSS Rules & Sheets:
js
window.cssLeakMetrics = {
getRuleCount: () => {
let totalRules = 0;
for (let i = 0; i < document.styleSheets.length; i++) {
try {
const sheet = document.styleSheets[i];
totalRules += sheet.cssRules ? sheet.cssRules.length : 0;
} catch (e) {} // CORS-blocked sheets
}
return totalRules;
},
getAnimations: () => document.querySelectorAll('[style*="animation"], [style*="transition"], *.animating').length,
getDetachedStyles: () => {
let detached = 0;
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
const el = walker.currentNode;
if (getComputedStyle(el).display === 'none' && el.offsetParent === null) {
// Heuristic: Detached but styled
detached++;
}
}
return detached;
}
};
setInterval(() => {
const rules = window.cssLeakMetrics.getRuleCount();
const anims = window.cssLeakMetrics.getAnimations();
const detached = window.cssLeakMetrics.getDetachedStyles();
console.table({rules, anims, detached});
if (rules > 10000) console.warn('[CSS-LEAK] High rule count!');
}, 2000);
-
Animation Leak Detector (using RAF for sampling):
Phase 4: Stress Test & Leak Simulation
-
Simulate Cycles (e.g., SPA nav):
code
// Repeat 10x: Trigger action (e.g., router.navigate('/')), takeSnapshot('after-cycle-X'), window.gc?.();
for (let i = 0; i < 10; i++) {
// YOUR LEAK TRIGGER HERE, e.g., unmountComponent();
setTimeout(() => takeSnapshot(`cycle-${i}`), 1000);
}
-
Take Heap Snapshots (DevTools Memory tab):
- Before/after cycles.
- Filter by
CSSStyleDeclaration, CSSStyleRule, Animation.
- Look for growing retainers (e.g., stylesheets → rules → DOM).
-
Stop Observers:
code
perfObserver.disconnect();
mutationObserver.disconnect();
clearInterval(memInterval);
Phase 5: Analysis & Remediation
| Symptom | Likely Cause | Fix |
|---|
Rising rules count | CSS-in-JS no cleanup | Scope stylesheets, use adoptedStyleSheets |
Growing anims | Unfinished transitions | animationend cleanup, cancelAnimationFrame |
High longtask | Recalc thrashing | Avoid deep class changes, use transform/opacity |
styleMutations floods | Dynamic <style> | Virtualize styles, remove on unmount |
Heap growth in CSSStyleDeclaration | ComputedStyle caches | Avoid storing getComputedStyle in closures |
Advanced Tips:
- Chrome Tracing: DevTools > Performance > Record, filter
RecalculateStyles.
- Lighthouse: Run audit for "Avoids enormous network payloads" (CSS bloat).
- Puppeteer Script: Automate for CI:
js
const puppeteer = require('puppeteer');
// Inject above scripts, assert heap < threshold.
Expected Output Example:
code
[CSS-LEAK] Heap: 45.2MB
[CSS-LEAK] Style mutation: {addedNodes: [<style> leaked-css</style>]}
rules: 12500 ← Alarm!
Run phases sequentially. If leak confirmed, bisect code (e.g., disable features). Share styleMutations/memSamples for further help!