Compose a CSS memory leak investigation playbook using PerformanceObserver,…
- User
Compose a CSS memory leak investigation playbook using PerformanceObserver, MutationObserver, and custom heuristics.
Assistant
The user wants a "playbook" for investigating CSS memory leaks. The key tools mentioned are
PerformanceObserver,MutationObserver, and "custom heuristics".Goal: Create a comprehensive guide/script collection that a developer can use to detect, diagnose, and understand CSS-related memory leaks in a web application.
Scope:
- Understanding the Problem: What does a CSS memory leak look like? (Usually detached DOM nodes holding onto styles, or increasing DOM size due to unremoved style tags/classes, or inefficient CSS selectors causing high memory usage during matching).
- Tools:
PerformanceObserver: Specifically looking for layout shifts, long tasks (rendering), or element counts (if accessible via performance APIs, thoughMemoryAPI is better for heap,PerformanceObserveris great for monitoring activity).MutationObserver: Tracking changes to the DOM (added/removed nodes, attribute changes) to see if cleanup is happening.- Custom Heuristics: Logic to analyze the data (e.g., rate of growth, specific class naming patterns, orphaned nodes).
- Structure of the Playbook:
- Phase 1: Setup/Injection: How to get this code running in the target app.
- Phase 2: Monitoring (The Observers): Code snippets for
PerformanceObserverandMutationObserver. - Phase 3: Analysis (The Heuristics): Logic to interpret the data.
- Phase 4: Remediation/Reporting: What to do with the findings.
Drafting the Content - Section by Section:
-
Introduction: Define what a CSS leak is. Usually, it's not just "CSS files" leaking, but Style retention. This happens when:
- DOM nodes are removed but not garbage collected (detached trees) because JS holds references, and these nodes have complex styles.
- Dynamic CSS injection (e.g., styled-components, JSS) where style tags are added but old ones never removed.
- CSSOM expansion (rare, but heavy styling).
-
The "Playbook" Format: It should look like a developer's field manual. Actionable, code-heavy.
-
Step 1: The DOM Sentinel (MutationObserver):
- We need to watch specific high-churn areas.
- Detect "Add" vs "Remove" balance.
- Heuristic: If
addedNodescount >removedNodescount over time, we have a leak candidate. - Heuristic: Check for specific attributes (class changes) that might indicate dynamic styling libraries.
- Code: A snippet that attaches to
document.body.
-
Step 2: The Style Injector Watchdog (MutationObserver - Head/Styles):
- Focus on
<style>tags and<link rel="stylesheet">. - Heuristic: Is the number of
<style>tags increasing linearly with user interaction? (Classic styled-components leak).
- Focus on
-
Step 3: The Runtime Monitor (PerformanceObserver):
- Type
element. - Actually,
PerformanceObserveris better for impact (Layout Thrashing, Recalculate Style). - Let's focus on
PerformanceObserverwith entry types'measure','layout-shift', and potentially'longtask'(though 'longtask' is often deprecated or moving, it's still standard enough). - Better idea: Use
PerformanceObserverto detect "Full GC" cycles if possible (not directly possible), but we can useperformance.memory(Chrome only) in a poller to correlate with DOM changes. - Let's stick to the prompt:
PerformanceObserver. We'll use it to measure Style Recalculation duration via the 'element' entry type or standard measures. Wait, theelementtiming entry type shows layout/paint timing. - Actually, a better use of
PerformanceObserverfor memory leaks is monitoring the volume of interactions vs performance hits.
- Type
-
Step 4: The Heuristics Engine (The "Brain"):
- This combines the inputs.
- Heuristic 1: The "Zombie Style" Counter. (Count style tags).
- Heuristic 2: The "Detached Forest" Scanner. (Walk the DOM looking for nodes not in the document but held in JS). This requires
WeakRefor just a snapshot analysis. - Let's refine the "Zombie" detection.
-
Code Structure:
- I'll create a JavaScript class
CSSLeakInvestigator. - It will contain methods for starting observers.
- It will output a report object.
- I'll create a JavaScript class
Refining the Heuristics:
- Rule of Constant Growth: If DOM node count goes up and never comes down during idle periods.
- Rule of Style Duplication: If multiple
<style>tags contain identical or highly similar CSS rules (common in CSS-in-JS without optimizations). - Rule of Complex Selectors: Analyzing the
document.styleSheetsto check selector complexity (less about leak, more about performance, but memory-related due to CSSOM size).
Self-Correction/Constraint Check:
- Prompt: "Compose a CSS memory leak investigation playbook..."
- Tone: Professional, technical, actionable.
- Tools:
PerformanceObserver,MutationObserver, Custom Heuristics.
Detailed Implementation Plan:
- Global Scope: We need to be careful not to cause the leak ourselves. Use
WeakReffor tracking elements if possible, but for simple counting, basic references are okay. - The
MutationObserverStrategy:- Target:
document.documentElement(covers body and head). - Config:
{ childList: true, subtree: true, attributes: true }. - Filter: look for
<style>,<link>, and elements withstyleattributes.
- Target:
- The
PerformanceObserverStrategy:- Use
performance.measureto wrap user actions? No, that requires instrumentation. - Let's use it to detect Long Animation Frames or standard interactions.
- Revised Strategy: The prompt asks for investigation.
PerformanceObserveris great for logging the cost of style recalculation. We can use theelementtiming or simply observe when style recalcs take too long (though standardPerformanceObserverdoesn't give raw "Recalc Style" events easily without DevTools protocol). - Pivot: Let's use
PerformanceObserverto listen forlayout-shiftandpaint. If layout shifts happen frequently without user input, it implies DOM instability often associated with injection/removal leaks. - Actually, let's define "Custom Heuristics" more broadly to include a Heap Snapshot simulation or DOM walker.
- Use
Writing the "Playbook" Output: I will structure it as:
- Mission Brief: What are we solving?
- The Toolkit: Explanation of the API choices.
- The Script (The Playbook): A comprehensive, copy-pasteable JS module.
- Heuristics Breakdown: Explaining the logic inside the script.
- Action Plan: How to run the investigation.
Specific Heuristics to Implement in Code:
- Style Tag Proliferation: Tracking
document.querySelectorAll('style').length. If it grows unbounded. - DOM Node Churn Ratio: (Added / Removed). If ratio > 1 consistently over time.
- Shadow DOM Penetration: Checking for unclosed Shadow Roots holding styles.
- Class Bloat: Tracking the number of classes on elements (average).
Let's write the code. I need a class that starts observing. It needs a
report()method. It needs to handledisconnect()cleanly.Feature: A "GC Pressure Test" function. Force garbage collection (if exposed, e.g., in Chrome with flags) or suggest window.idle.
CSS Specifics: Memory leaks in CSS are almost always about the DOM elements holding the styles or Style Tags accumulating. So
MutationObserveris the primary weapon.PerformanceObserveris for symptom detection (slowness).Let's refine the
PerformanceObserverpart. It observesentryTypes: ['measure', 'resource', 'element', 'longtask']. If we seelongtaskright after a Mutation batch, we have a suspect.Final Polish: Ensure the code is modern (ES6+), uses requestIdleCallback for checking to avoid impact, and provides clear console output.
Heuristic Logic Check:
- Scenario: React app with styled-components.
- Leak: Every component mount adds a
<style>tag. Unmount doesn't remove it. - Detection: MutationObserver sees
addedNodes: [style]. Later sees no removal. Counter increments. - Scenario: App creates divs, removes them, but keeps a JS array reference.
- Detection: DOM count (document.getElementsByTagName('*').length) goes up and down? No, if they are detached, they aren't in
document. - Limitation:
document.querySelectorAllonly sees the attached DOM. - Crucial Addition: To see detached nodes, we need the Heap Snapshot.
- Playbook Adjustment: Since we cannot access Heap Snapshot via JS API, we must infer leaks via "Style Tag Count" and "Attached Node Growth" (which is a memory leak of attached nodes).
- We can use
performance.memory(non-standard but supported in Chrome) to track actual memory usage and correlate it with DOM mutations.
Final Plan for the Response:
- Concept: Define the "Leak Vectors" (Style Tags, Attached DOM growth).
- Code: Provide a
CSSLeakInvestigatorclass.- Constructor: Setup maps for tracking.
start(): Init MutationObserver (Body & Head) and PerformanceObserver.check(): Run heuristics (Memory vs DOM size, Style tag count).report(): Print findings.
- Manual Steps: Explain how to interpret the data using Chrome DevTools alongside this script.
Let's go. A comprehensive playbook for investigating CSS memory leaks requires moving beyond simple snapshot analysis. We need to observe the lifecycle of styles in real-time.
This playbook introduces a Live Diagnostics Script that uses
MutationObserverto track DOM and Stylesheet changes,PerformanceObserverto correlate layout thrashing, and custom heuristics to detect "Zombie CSS" (styles that persist after their elements are gone).Phase 1: The Investigation Toolkit
Copy and paste the following module into your browser's DevTools console (or embed it in your app during staging).
/** * CSS MEMORY LEAK INVESTIGATOR * A runtime playbook for detecting zombie styles and stylesheet bloat. */ const CSSLeakInvestigator = (() => { // State containers const state = { isRunning: false, styleRegistry: new Map(), // Tracks <style> and <link> nodes classRegistry: new Set(), // Tracks classes applied to DOM elements orphans: [], // Detected suspicious patterns metrics: { styleNodeCount: 0, domNodeCount: 0, lastCheckTime: 0 } }; const config = { threshold: { // Heuristic: If a stylesheet has > 500 rules but affects < 5 elements inefficiencyRatio: 100, // Heuristic: Max number of <style> tags allowed (React Styled Components often leak this way) maxStyleTags: 50, } }; // --------------------------------------------------------- // 1. MUTATION OBSERVER: The Sentinel // --------------------------------------------------------- const sentinel = new MutationObserver((mutations) => { if (!state.isRunning) return; mutations.forEach(mutation => { // A. Track Added Nodes (Inbound Leaks) mutation.addedNodes.forEach(node => { if (node.nodeType === 1) { // Element Node // Check for inline styles or injected style tags if (node.tagName === 'STYLE') { registerStyleTag(node); } // Harvest classes from new elements harvestClasses(node); } }); // B. Track Removed Nodes (Cleanup Verification) mutation.removedNodes.forEach(node => { if (node.nodeType === 1 && node.tagName === 'STYLE') { // Note: We don't delete from registry immediately to detect "detached" refs if possible console.warn(`[Cleanup] <style> tag removed. Text content length: ${node.textContent?.length}`); } }); }); }); // --------------------------------------------------------- // 2. PERFORMANCE OBSERVER: The Cost Monitor // --------------------------------------------------------- const costMonitor = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.forEach(entry => { // Heuristic: Layout shifts or long recalc styles often accompany CSS bloat if (entry.entryType === 'layout-shift' && entry.value > 0.1) { console.warn(`[Performance] High Layout Shift (${entry.value.toFixed(4)}) detected. Potential CSSOM thrash.`); } if (entry.entryType === 'measure') { console.log(`[Measure] ${entry.name}: ${entry.duration}ms`); } }); }); // --------------------------------------------------------- // 3. HEURISTICS ENGINE // --------------------------------------------------------- /** * Heuristic 1: Stylesheet Bloat * Checks if the number of active <style> tags is suspiciously high. */ const checkStyleSheetBloat = () => { const styles = document.querySelectorAll('style'); const count = styles.length; if (count > config.threshold.maxStyleTags) { const msg = `LEAK SUSPECT: Found ${count} <style> tags. Limit is ${config.threshold.maxStyleTags}. Likely caused by CSS-in-JS library without injection cache.`; console.error(msg); return msg; } return null; }; /** * Heuristic 2: The "Zombie" Selector * Scans stylesheets for rules that define classes that do not exist in the current DOM. * Warning: Expensive operation. Do not run in loop. */ const scanForZombieSelectors = () => { const sheets = document.styleSheets; let zombieCount = 0; // Update our registry of what classes currently exist updateClassRegistry(); try { for (let sheet of sheets) { try { // Rules may be restricted by CORS const rules = sheet.cssRules || sheet.rules; for (let rule of rules) { if (rule.styleSheet) continue; // Skip nested imports for now // Simple heuristic: Check selector text against live DOM // Note: This is a rough check. Complex selectors (e.g., .a > .b) need parsing. const selectorText = rule.selectorText; if (selectorText) { const classes = selectorText.match(/\.[a-zA-Z_-][\w-]*/g); if (classes) { // Check if ANY class in the selector exists in our registry const foundInDom = classes.some(cls => { // Strip the dot const className = cls.substring(1); return state.classRegistry.has(className); }); // If the selector is a pure class selector (no tags) and not found if (!foundInDom && selectorText.startsWith('.')) { zombieCount++; } } } } } catch (e) { // CORS error on stylesheet, ignore } } } catch (err) { console.error("Error scanning sheets", err); } console.log(`[Heuristic] Scan complete. Approximate unused rule definitions: ${zombieCount}`); return zombieCount; }; // --------------------------------------------------------- // HELPERS // --------------------------------------------------------- const registerStyleTag = (node) => { const id = node.id || (Math.random().toString(36).substring(2, 8)); const size = node.textContent.length; state.styleRegistry.set(id, { node, size, time: Date.now() }); console.log(`[Registry] New Style Tag Added. Size: ${size}b. Total Tags: ${state.styleRegistry.size}`); }; const harvestClasses = (node) => { if (node.classList) { node.classList.forEach(cls => state.classRegistry.add(cls)); } }; const updateClassRegistry = () => { // Re-scan the whole body to ensure registry is accurate document.querySelectorAll('*').forEach(el => { if (el.classList) el.classList.forEach(cls => state.classRegistry.add(cls)); }); }; // --------------------------------------------------------- // PUBLIC API // --------------------------------------------------------- return { start: () => { state.isRunning = true; sentinel.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style'] }); try { costMonitor.observe({ type: 'layout-shift', buffered: true }); costMonitor.observe({ type: 'measure', buffered: true }); } catch(e) { console.warn("PerformanceObserver types not fully supported", e); } console.log("🕵️♂️ CSS Leak Investigation Started..."); }, stop: () => { state.isRunning = false; sentinel.disconnect(); costMonitor.disconnect(); console.log("🛑 Investigation Stopped."); }, runDiagnostics: () => { console.group("🔬 CSS LEAK REPORT"); // 1. Check Style Tag Count const bloatResult = checkStyleSheetBloat(); // 2. Check Memory Correlation if (performance.memory) { const usedMB = (performance.memory.usedJSHeapSize / 1048576).toFixed(2); const totalMB = (performance.memory.totalJSHeapSize / 1048576).toFixed(2); console.log(`[Memory] Heap: ${usedMB}MB / ${totalMB}MB`); console.log(`[DOM] Node Count: ${document.getElementsByTagName('*').length}`); } // 3. Run Zombie Scan (Expensive) console.log("Running Zombie Selector Scan (this may take a moment)..."); const zombies = scanForZombieSelectors(); console.groupEnd(); return { styleTags: state.styleRegistry.size, zombieRules: zombies, isBloated: !!bloatResult }; } }; })(); // Usage: // CSSLeakInvestigator.start(); // ... interact with app ... // CSSLeakInvestigator.runDiagnostics(); // CSSLeakInvestigator.stop();
Phase 2: The Playbook Execution
Follow these steps to isolate the leak.
Step 1: Establish a Baseline
- Open your application.
- Run
CSSLeakInvestigator.start(). - Do not interact. Wait 5 seconds.
- Run
CSSLeakInvestigator.runDiagnostics(). - Note the "Style Node Count" and "Zombie Rules".
Step 2: The Action Loop
Perform the specific action you suspect is causing the leak (e.g., opening and closing a Modal, switching tabs, filtering a list).
- Open the Modal.
- Close the Modal.
- Repeat 5–10 times.
Step 3: Analyze Heuristics
Run
CSSLeakInvestigator.runDiagnostics()again.Heuristic A: The
<style>Accumulator- Symptom: The console warns "LEAK SUSPECT: Found 55 tags."
- Diagnosis: This is common in CSS-in-JS libraries (like styled-components or Emotion) if the insertion point is misconfigured or if components unmount without cleaning up the injected style tags.
- Fix: Check your library config for
speedymode or injection points. Ensurecacheis shared across the app.
Heuristic B: The Zombie Selector
- Symptom: High "Zombie Rules" count.
- Diagnosis: You have CSS files (possibly loaded via
import()) that define styles for components that are not currently rendered. While this isn't strictly a "leak" (browsers handle this efficiently), a massive amount of unused CSS slows down the Style Recalculation phase. - Fix: Implement code-splitting for CSS or use PurgeCSS.
Heuristic C: MutationObserver Silence
- Symptom: You see memory usage growing in Chrome Task Manager, but
runDiagnosticsshows stable Style Tags. - Diagnosis: The leak is likely Retained DOM (JavaScript holding references to detached DOM nodes). Since the nodes are detached, the
MutationObserversees the removal, but the Garbage Collector cannot free them because a JS variable still points to them. - Fix: Use the Heap Snapshot tool in Chrome DevTools. Filter for "Detached DOM nodes".
Phase 3: Advanced Intervention (Manual)
If the automated script doesn't find it, use the "Force Garbage Collection" technique.
- Open Chrome DevTools -> Performance tab.
- Click Record.
- Perform the "Action Loop" (Open/Close Modal).
- Click the Trash Can icon (Collect Garbage).
- Stop Recording.
- Look at the Summary tab. If "Nodes" or "Listeners" does not drop after the trash can click, you have a hard leak.
- Specifically look at the CSS Style Sheets counter in the timeline. If it trends upward and flatlines after GC, you have a leaked StyleSheet object.
Summary of Common Culprits
Suspect Likely Cause Heuristic Trigger JSS/Styled-Components Missing speedyflag or unoptimized component mounting.High <style>count.Third-Party Widgets Chat widgets or embeds injecting global overrides. MutationObserverlogs unknown<style>additions.Animation Libraries (e.g., GSAP/Anime.js) Creating inline style loops that never resolve. PerformanceObserverwarning about Layout Shift/Recalc.SPA Routing CSS from previous route not being unloaded. Rising "Zombie Rules" count on route change.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.