We are going to create a playbook for investigating potential memory leaks in a web application using:
- PerformanceObserver to monitor long tasks and other performance metrics that might indicate jank or memory issues.
- MutationObserver to watch for unexpected DOM changes that might accumulate (like adding many nodes without removal).
- Custom heuristics based on monitoring the number of DOM nodes, event listeners, and other objects that might be leaking.
Steps:
-
Setup PerformanceObserver:
- We'll observe
longtask entries to see if there are tasks taking too long (which might be due to memory pressure or large amounts of work).
- Also, we can observe
gc (if available) to see when garbage collection happens, and if there are long pauses, that might indicate memory issues.
-
Setup MutationObserver:
- We'll watch for added nodes and removed nodes. We can keep a count of added nodes and removed nodes and see if the net count keeps growing.
- We can also watch for attribute changes that might be adding event listeners or other resources.
-
Custom Heuristics:
- Monitor the total number of DOM nodes (by
document.querySelectorAll('*').length). We can take snapshots at intervals and see if it grows unexpectedly.
- Monitor the number of event listeners (though there's no direct API, we can try to estimate by counting
onclick etc. and using getEventListeners in Chrome devtools but note that getEventListeners is not a standard API and only available in devtools). Alternatively, we can instrument our own code to track event listener registration.
- We can also monitor memory usage via
performance.memory (non-standard, Chrome only) and look for trends.
-
Logging and Reporting:
- We'll set up a way to log the findings (console, or send to a server) and set thresholds for alerts.
-
Simulating Garbage Collection:
- We can try to force garbage collection (if available) and see if memory drops. Note:
window.gc() is only available if Chrome is started with --js-flags="--expose-gc" and in devtools.
-
Taking Heap Snapshots (if in devtools):
- We can't programmatically take heap snapshots in production, but in dev we can use
window.chrome or performance.memory to get an idea.
However, note that we are writing a playbook for investigation, so we are going to write a script that can be run in the browser console or injected to monitor and report.
Let's structure the code:
We'll create a class MemoryLeakInvestigatior that:
- Initializes the observers and heuristics.
- Starts monitoring.
- Provides a way to stop and report.
But note: We cannot rely on performance.memory in all browsers and getEventListeners is devtools only.
So we have to be cautious and design for what is available.
Steps in code:
-
PerformanceObserver for long tasks and maybe gc (if available).
-
MutationObserver for DOM changes.
-
Set intervals to:
- Count DOM nodes.
- Try to get memory info (if available).
- Compare with previous measurements and log if there's a significant increase.
-
We'll also keep a count of mutations (additions/removals) and log the net change.
-
We can also monitor the number of setTimeout/setInterval calls? (But note, they are stored in the timer list, and there's no direct API to count.)
-
We can also monitor the number of WebSocket connections? (Again, no direct API.)
Given the limitations, we focus on what we can observe.
Implementation:
We'll create:
class MemoryLeakInvestigator {
constructor(options = {}) {
this.options = {
logThreshold: 100, // log if DOM nodes increase by this much in an interval
longTaskThreshold: 50, // ms, log if a long task takes more than this
memoryThreshold: 10 * 1024 * 1024, // 10MB, log if memory increases by this much (if available)
...options
};
this.domNodeCount = 0;
this.memoryInfo = null;
this.mutationCount = { added: 0, removed: 0 };
this.performanceObserver = null;
this.mutationObserver = null;
this.intervalId = null;
}
start() {
this._setupPerformanceObserver();
this._setupMutationObserver();
this._setupInterval();
}
stop() {
if (this.performanceObserver) {
this.performanceObserver.disconnect();
}
if (this.mutationObserver) {
this.mutationObserver.disconnect();
}
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
_setupPerformanceObserver() {
// Long tasks
this.performanceObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > this.options.longTaskThreshold) {
console.warn(`Long task detected: ${entry.duration}ms`, entry);
}
}
});
this.performanceObserver.observe({ entryTypes: ['longtask'] });
// If 'gc' is supported, we can also observe that.
if (PerformanceObserver.supportedEntryTypes && PerformanceObserver.supportedEntryTypes.includes('gc')) {
const gcObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('GC event:', entry);
}
});
gcObserver.observe({ entryTypes: ['gc'] });
}
}
_setupMutationObserver() {
this.mutationObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
this.mutationCount.added += mutation.addedNodes.length;
this.mutationCount.removed += mutation.removedNodes.length;
// Log if we have a lot of added nodes without removal?
}
}
});
this.mutationObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true // we might want to watch attribute changes that set event handlers?
});
}
_setupInterval() {
this.intervalId = setInterval(() => {
this._collectMetrics();
this._reportMetrics();
}, 5000); // every 5 seconds
}
_collectMetrics() {
// Count DOM nodes
const currentDomCount = document.querySelectorAll('*').length;
const domChange = currentDomCount - this.domNodeCount;
this.domNodeCount = currentDomCount;
// Memory info (Chrome only)
let memoryChange = 0;
if (performance.memory) {
const currentMemory = performance.memory.usedJSHeapSize;
if (this.memoryInfo) {
memoryChange = currentMemory - this.memoryInfo.usedJSHeapSize;
}
this.memoryInfo = performance.memory;
}
// Log if thresholds are exceeded
if (Math.abs(domChange) > this.options.logThreshold) {
console.warn(`DOM node count changed by ${domChange} (now ${this.domNodeCount})`);
}
if (memoryChange > this.options.memoryThreshold) {
console.warn(`Memory increased by ${memoryChange} bytes (now ${this.memoryInfo.usedJSHeapSize})`);
}
// Also log mutation count (net change)
const netMutation = this.mutationCount.added - this.mutationCount.removed;
if (Math.abs(netMutation) > this.options.logThreshold) {
console.warn(`Net mutation count: ${netMutation} (added: ${this.mutationCount.added}, removed: ${this.mutationCount.removed})`);
}
// Reset mutation count for next interval? Or keep cumulative? Let's reset so we see per interval.
this.mutationCount = { added: 0, removed: 0 };
}
_reportMetrics() {
// We can also send to a server or store in an array for later analysis.
// For now, we just log.
}
}
However, note:
- The
performance.memory is non-standard and only in Chrome.
- The
getEventListeners is only in devtools.
We can try to approximate event listeners by:
- Counting elements with
onclick etc. but that only catches inline handlers.
- We could override
addEventListener to count, but that only catches our overrides and might break things.
So we might not be able to get event listener count reliably.
Alternatively, we can use the Chrome DevTools Protocol (CDP) to get event listeners, but that's not available in the page context.
So we have to accept that we cannot get event listeners from the page.
But we can try:
- Overriding
EventTarget.addEventListener and removeEventListener to keep a count (but note: multiple calls for the same element and event type, and also passive, once, etc. are options). This is invasive and might break if done incorrectly.
Let's not do that in this playbook because it's risky.
Instead, we focus on:
- DOM nodes
- Memory (if available)
- Long tasks
- Mutations
We can also try to monitor:
setTimeout and setInterval counts? We can override them to count active timers.
Let's try:
let timerCount = 0;
const originalSetTimeout = window.setTimeout;
window.setTimeout = function(...args) {
timerCount++;
return originalSetTimeout(...args);
};
// Similarly for clearTimeout? But we don't know when they are cleared.
// We can't track clearTimeout without also overriding it and then decrementing, but note that the same timer id might be reused? And also we don't know if the timer is cleared by the system (like when the page is unloaded). So this is also not perfect.
// Alternatively, we can use `window.performance.getEntriesByType('resource')` to see if there are many resources (images, scripts) that are not released? But that's a different kind of leak.
// We'll stick to the main ones.
Given the complexity and non-standard APIs, we might have to rely on the user to run this in Chrome and use devtools for more details.
So the playbook:
- Run the above
MemoryLeakInvestigator in the console (or inject it).
- Let it run for a while (while using the app) and watch the console for warnings.
- If we see DOM nodes increasing, we can use
console.log to see the net change and then use the Elements panel to see if there are nodes that should have been removed.
- If we see memory increasing, we can use the Memory panel in devtools to take heap snapshots and compare.
We can also add a feature to take a heap snapshot programmatically? Not really, because window.heapSnapshot is not available.
But we can try to use console.profile and console.profileEnd to start and stop a profiling session? That's for CPU, not memory.
So the script is more of a early warning system.
Let's adjust the code to also log the current performance.memory (if available) at each interval.
We'll also add an option to log every interval (without threshold) for debugging.
Revised:
class MemoryLeakInvestigator {
constructor(options = {}) {
this.options = {
logThreshold: 100,
longTaskThreshold: 50,
memoryThreshold: 10 * 1024 * 1024,
logEveryInterval: false, // set to true to log every interval
...options
};
this.domNodeCount = 0;
this.memoryInfo = null;
this.mutationCount = { added: 0, removed: 0 };
this.performanceObserver = null;
this.mutationObserver = null;
this.intervalId = null;
this.intervalCount = 0;
}
start() {
this._setupPerformanceObserver();
this._setupMutationObserver();
this._setupInterval();
}
stop() {
if (this.performanceObserver) {
this.performanceObserver.disconnect();
}
if (this.mutationObserver) {
this.mutationObserver.disconnect();
}
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
_setupPerformanceObserver() {
this.performanceObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > this.options.longTaskThreshold) {
console.warn(`Long task detected: ${entry.duration}ms`, entry);
}
}
});
this.performanceObserver.observe({ entryTypes: ['longtask'] });
if (PerformanceObserver.supportedEntryTypes && PerformanceObserver.supportedEntryTypes.includes('gc')) {
const gcObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('GC event:', entry);
}
});
gcObserver.observe({ entryTypes: ['gc'] });
}
}
_setupMutationObserver() {
this.mutationObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
this.mutationCount.added += mutation.addedNodes.length;
this.mutationCount.removed += mutation.removedNodes.length;
}
}
});
this.mutationObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true
});
}
_setupInterval() {
this.intervalId = setInterval(() => {
this.intervalCount++;
this._collectMetrics();
this._reportMetrics();
}, 5000);
}
_collectMetrics() {
const currentDomCount = document.querySelectorAll('*').length;
const domChange = currentDomCount - this.domNodeCount;
this.domNodeCount = currentDomCount;
let memoryChange = 0;
if (performance.memory) {
const currentMemory = performance.memory.usedJSHeapSize;
if (this.memoryInfo) {
memoryChange = currentMemory - this.memoryInfo.usedJSHeapSize;
}
this.memoryInfo = performance.memory;
}
// Store the changes for reporting
this.lastMetrics = {
domChange,
currentDomCount,
memoryChange,
currentMemory: this.memoryInfo ? this.memoryInfo.usedJSHeapSize : null,
netMutation: this.mutationCount.added - this.mutationCount.removed,
addedNodes: this.mutationCount.added,
removedNodes: this.mutationCount.removed,
timestamp: Date.now()
};
// Reset mutation count for next interval
this.mutationCount = { added: 0, removed: 0 };
// Check thresholds
if (Math.abs(domChange) > this.options.logThreshold) {
console.warn(`[${this.intervalCount}] DOM node count changed by ${domChange} (now ${this.domNodeCount})`);
}
if (memoryChange > this.options.memoryThreshold) {
console.warn(`[${this.intervalCount}] Memory increased by ${memoryChange} bytes (now ${this.memoryInfo.usedJSHeapSize})`);
}
const netMutation = this.lastMetrics.netMutation;
if (Math.abs(netMutation) > this.options.logThreshold) {
console.warn(`[${this.intervalCount}] Net mutation count: ${netMutation} (added: ${this.lastMetrics.addedNodes}, removed: ${this.lastMetrics.removedNodes})`);
}
}
_reportMetrics() {
if (this.options.logEveryInterval) {
console.log(`[${this.intervalCount}] Metrics:`, this.lastMetrics);
}
}
}
Usage:
const investigator = new MemoryLeakInvestigator({ logThreshold: 50, logEveryInterval: true });
investigator.start();
Then, after using the app, you can call investigator.stop() and look at the logs.
If you see a steady increase in DOM nodes or memory, that's a sign of a leak.
But note: The DOM node count can fluctuate due to normal operation. We are looking for a consistent upward trend.
We can also enhance by storing the history and then computing the trend.
Let's add a history and a way to get a report:
class MemoryLeakInvestigator {
// ... previous code ...
constructor(options = {}) {
// ...
this.history = [];
}
_collectMetrics() {
// ... same as before until storing ...
this.lastMetrics = {
// ... same fields ...
};
this.history.push(this.lastMetrics);
// Keep only last 100 intervals to avoid memory leak in our own script?
if (this.history.length > 100) {
this.history.shift();
}
// ... thresholds and reset ...
}
getReport() {
// Compute trends over the history
let domTrend = 0;
let memoryTrend = 0;
let mutationTrend = 0;
if (this.history.length > 1) {
const first = this.history[0];
const last = this.history[this.history.length - 1];
domTrend = last.currentDomCount - first.currentDomCount;
memoryTrend = last.currentMemory - first.currentMemory;
mutationTrend = last.netMutation - first.netMutation; // Not exactly, because netMutation is per interval. We want total added minus removed?
// Actually, we want the total change in DOM nodes and memory over the entire history.
// For mutations, we want the total added and removed? Let's calculate:
const totalAdded = this.history.reduce((sum, m) => sum + m.addedNodes, 0);
const totalRemoved = this.history.reduce((sum, m) => sum + m.removedNodes, 0);
mutationTrend = totalAdded - totalRemoved;
}
return {
historyLength: this.history.length,
domTrend, // change in total DOM nodes from first to last
memoryTrend, // change in memory (bytes)
mutationTrend, // net number of nodes added (total added - total removed)
currentDomCount: this.domNodeCount,
currentMemory: this.memoryInfo ? this.memoryInfo.usedJSHeapSize : null,
totalAdded: this.history.reduce((sum, m) => sum + m.addedNodes, 0),
totalRemoved: this.history.reduce((sum, m) => sum + m.removedNodes, 0)
};
}
}
Then you can call investigator.getReport() to see the trends.
This is a basic playbook. We can extend it with more heuristics and better reporting.
Important: This script itself might cause some memory usage, so we should be cautious and not run it for too long without monitoring its own impact.
Also, note that querySelectorAll('*') on a large DOM can be expensive, so we might want to do it less frequently? But we are doing every 5 seconds, which might be acceptable.
Alternatively, we can use document.getElementsByTagName('*').length which might be faster? Not sure.
Let's keep it as is.
Final note: This is for investigation, not for production. We are running it in the console or as a bookmarklet.
We can also try to monitor:
- The number of iframes? (document.getElementsByTagName('iframe').length)
- The number of images? (document.images.length)
But again, we are limited by what we can access.
Let's stick to the above and extend as needed.
Now, let's write the complete code with the report feature.
We'll also add a method to force a garbage collection (if available) and then measure memory again.
But note: window.gc() is not available by default.
We can try:
if (window.gc) {
window.gc();
}
So we can add a method:
forceGC() {
if (window.gc) {
window.gc();
console.log('Forced garbage collection');
// Wait a bit and then collect metrics again?
setTimeout(() => this._collectMetrics(), 100);
} else {
console.warn('gc() is not available. Run Chrome with --js-flags="--expose-gc"');
}
}
But note: forcing GC might affect the performance of the page and is generally not recommended in production.
We'll leave it as an optional method.
Let's put it all together.
CSS Memory Leak Investigation Playbook
🎯 Objective
Systematically identify and diagnose memory leaks related to CSS/DOM interactions using browser APIs and custom heuristics.
📋 Prerequisites
- Chrome/Edge DevTools (preferred for
performance.memory API)
- Node.js (optional, for heap snapshot analysis)
- Browser console access (no script blockers)
--js-flags="--expose-gc" for manual GC testing (Chrome only)
🔧 Toolkit Setup
1. Core Monitoring Script
// memory-investigator.js - Inject this into console or as bookmarklet
class CSSMemoryLeakInvestigator {
constructor(options = {}) {
this.config = {
sampleInterval: 5000, // ms between measurements
domThreshold: 1000, // warn if DOM nodes increase by this
longTaskThreshold: 50, // ms for long task detection
gcForceInterval: 30000, // force GC attempt frequency
maxHistory: 100, // max data points to store
...options
};
this.metrics = {
domNodeCount: [],
memoryUsed: [],
mutationRates: [],
longTasks: [],
detachedElements: []
};
this.observers = new Map();
this.startTime = Date.now();
}
start() {
console.log('🔍 Starting CSS Memory Leak Investigation...');
this._setupPerformanceObserver();
this._setupMutationObserver();
this._setupIntervalSampling();
this._setupDetachedElementTracking();
}
stop() {
this.observers.forEach(obs => obs.disconnect());
clearInterval(this.samplingInterval);
console.log('⏹️ Investigation stopped');
}
_setupPerformanceObserver() {
// Monitor long tasks
if (!this.observers.has('longtask')) {
constobserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > this.config.longTaskThreshold) {
this.metrics.longTasks.push({
duration: entry.duration,
start: entry.startTime,
timestamp: Date.now()
});
console.warn(`⚠️ Long task detected: ${entry.duration.toFixed(2)}ms`);
}
}
});
longtaskObserver.observe({ entryTypes: ['longtask'] });
this.observers.set('longtask', longtaskObserver);
}
// Monitor memory (Chrome only)
if (performance.memory) {
setInterval(() => {
const mem = performance.memory;
this.metrics.memoryUsed.push({
used: mem.usedJSHeapSize,
total: mem.totalJSHeapSize,
limit: mem.jsHeapSizeLimit,
timestamp: Date.now()
});
// Detect upward trend
if (this.metrics.memoryUsed.length > 5) {
const recent = this.metrics.memoryUsed.slice(-5);
const trend = recent[4].used - recent[0].used;
if (trend > 5 * 1024 * 1024) { // 5MB increase in 25s
console.warn(`📈 Memory trending up: ${(trend/1048576).toFixed(2)}MB`);
}
}
}, this.config.sampleInterval);
}
}
_setupMutationObserver() {
const mutationObserver = new MutationObserver((mutations) => {
let addedCount = 0, removedCount = 0;
mutations.forEach(mutation => {
addedCount += mutation.addedNodes.length;
removedCount += mutation.removedNodes.length;
// Heuristic: Many added nodes without corresponding removes
if (mutation.addedNodes.length > 50) {
console.warn(`⚠️ Large DOM insertion: ${mutation.addedNodes.length} nodes`);
}
});
this.metrics.mutationRates.push({
added: addedCount,
removed: removedCount,
net: addedCount - removedCount,
timestamp: Date.now()
});
// Calculate running DOM count (approximate)
if (this.metrics.domNodeCount.length > 0) {
const lastCount = this.metrics.domNodeCount[this.metrics.domNodeCount.length - 1].count;
const newCount = lastCount + (addedCount - removedCount);
this.metrics.domNodeCount.push({
count: newCount,
timestamp: Date.now()
});
if (Math.abs(newCount - lastCount) > this.config.domThreshold) {
console.warn(`📊 DOM node count changed by ${newCount - lastCount}`);
}
} else {
this.metrics.domNodeCount.push({
count: document.querySelectorAll('*').length,
timestamp: Date.now()
});
}
});
mutationObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: false // We handle CSS separately
});
this.observers.set('mutation', mutationObserver);
}
_setupDetachedElementTracking() {
// Track detached elements via MutationObserver on documentFragment
const fragObserver = new MutationObserver((mutations) => {
const detached = [];
document.querySelectorAll('*').forEach(el => {
if (!el.isConnected && el.tagName) {
detached.push({
tag: el.tagName,
id: el.id,
classes: el.className,
cssText: el.style.cssText.substring(0, 100) + '...'
});
}
});
if (detached.length > 0) {
this.metrics.detachedElements.push({
count: detached.length,
samples: detached.slice(0, 10), // Store first 10 samples
timestamp: Date.now()
});
if (detached.length > 100) {
console.warn(`👻 ${detached.length} detached elements detected!`);
}
}
});
// Observe when elements become detached
const trackDetach = setInterval(() => fragObserver.observe(document, { childList: true, subtree: true }), 2000);
this.observers.set('detached', fragObserver);
this.observers.set('trackInterval', { disconnect: () => clearInterval(trackDetach) });
}
_setupIntervalSampling() {
this.samplingInterval = setInterval(() => {
this._takeSnapshot();
}, this.config.sampleInterval);
}
_takeSnapshot() {
const snapshot = {
timestamp: Date.now(),
domCount: document.querySelectorAll('*').length,
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null,
cssRules: this._countCSSRules(),
styleSheets: document.styleSheets.length,
computedStyles: this._sampleComputedStyles()
};
console.log(`📸 Snapshot [${(snapshot.timestamp - this.startTime)/1000}s]:`,
`DOM: ${snapshot.domCount} nodes, ` +
`CSS: ${snapshot.cssRules} rules, ` +
`Sheets: ${snapshot.styleSheets}`);
}
_countCSSRules() {
let count = 0;
for (let i = 0; i < document.styleSheets.length; i++) {
try {
count += document.styleSheets[i].cssRules.length;
} catch (e) {
// CORS or other access restrictions
count += 0;
}
}
return count;
}
_sampleComputedStyles() {
// Sample 10 random elements for computed style analysis
const samples = [];
const allElements = document.querySelectorAll('*');
const step = Math.max(1, Math.floor(allElements.length / 10));
for (let i = 0; i < allElements.length; i += step) {
const el = allElements[i];
const style = getComputedStyle(el);
samples.push({
tag: el.tagName,
cssText: style.cssText.substring(0, 200) + '...',
propertyCount: style.length
});
if (samples.length >= 10) break;
}
return samples;
}
forceGC() {
if (window.gc) {
console.log('🧹 Forcing garbage collection...');
window.gc();
setTimeout(() => {
console.log('Post-GC memory:', performance.memory);
}, 100);
} else {
console.warn('gc() not available. Launch Chrome with: --js-flags="--expose-gc"');
}
}
generateReport() {
const report = {
duration: Date.now() - this.startTime,
summary: this._generateSummary(),
anomalies: this._detectAnomalies(),
recommendations: this._generateRecommendations(),
rawData: {
domNodeHistory: this.metrics.domNodeCount,
memoryHistory: this.metrics.memoryUsed,
longTasks: this.metrics.longTasks,
detachedElements: this.metrics.detachedElements
}
};
console.table(report.summary);
console.log('🚨 Anomalies:', report.anomalies);
console.log('💡 Recommendations:', report.recommendations);
return report;
}
_generateSummary() {
const domChanges = this.metrics.domNodeCount;
const memoryChanges = this.metrics.memoryUsed;
return {
'Total Samples': domChanges.length,
'Net DOM Change': domChanges.length > 1 ?
domChanges[domChanges.length-1].count - domChanges[0].count : 0,
'Peak Memory (MB)': memoryChanges.length > 0 ?
Math.max(...memoryChanges.map(m => m.used/1048576)).toFixed(2) : 'N/A',
'Total Long Tasks': this.metrics.longTasks.length,
'Detached Element Incidents': this.metrics.detachedElements.length,
'Avg Mutation Rate': this._avg(this.metrics.mutationRates.map(r => r.net))
};
}
_detectAnomalies() {
const anomalies = [];
// DOM growth pattern
if (this.metrics.domNodeCount.length > 10) {
const recent = this.metrics.domNodeCount.slice(-10);
const growth = recent[recent.length-1].count - recent[0].count;
if (growth > 500) {
anomalies.push(`Steady DOM growth: +${growth} nodes in last ${this.config.sampleInterval * 10/1000}s`);
}
}
// Memory without GC
if (this.metrics.memoryUsed.length > 20) {
const last20 = this.metrics.memoryUsed.slice(-20);
const memorySlope = this._calculateSlope(last20.map(m => m.used));
if (memorySlope > 1024 * 100) { // >100KB/s
anomalies.push(`Memory increasing at ${(memorySlope/1024).toFixed(1)}KB/s without GC`);
}
}
// Detached elements accumulation
const detachedCounts = this.metrics.detachedElements.map(d => d.count);
if (detachedCounts.some(c => c > 50)) {
anomalies.push(`Large detached elements detected: ${Math.max(...detachedCounts)} max`);
}
return anomalies;
}
_generateRecommendations() {
const recs = [];
if (this._detectAnomalies().length > 0) {
recs.push('1. Check for event listener accumulation (use getEventListeners in console)');
recs.push('2. Inspect CSS animations/transitions that may not be cleaned up');
recs.push('3. Review Web Components for shadow DOM leaks');
recs.push('4. Check for CSS-in-JS style objects not being garbage collected');
recs.push('5. Audit third-party libraries for known memory issues');
recs.push('6. Use Chrome Memory tab: Heap snapshot > Comparison view');
recs.push('7. Test with Chrome Task Manager (Shift+Esc) - watch "JS Heap"');
}
return recs;
}
_avg(arr) {
return arr.length ? arr.reduce((a,b) => a+b, 0)/arr.length : 0;
}
_calculateSlope(data) {
if (data.length < 2) return 0;
const n = data.length;
const sumX = n * (n-1) / 2;
const sumY = data.reduce((a,b) => a+b, 0);
const sumXY = data.reduce((sum, y, x) => sum + x*y, 0);
return (n * sumXY - sumX * sumY) / (n * sumX - sumX * sumX);
}
}
// Usage
const investigator = new CSSMemoryLeakInvestigator({
logThreshold: 500,
longTaskThreshold: 100
});
investigator.start();
// Later...
investigator.generateReport();
🔍 Investigation Workflow
Phase 1: Baseline Establishment
// 1. Clear existing data
localStorage.clear();
sessionStorage.clear();
location.reload();
// 2. Start with clean slate
const investigator = new CSSMemoryLeakInvestigator();
investigator.start();
// 3. Record baseline (idle state)
setTimeout(() => {
console.log('Baseline recorded. Begin user interaction...');
}, 10000);
Phase 2: Reproduction
- Perform target user flow (click, navigate, open/close modals, etc.)
- Repeat 5-10 times to establish pattern
- Monitor console for warnings
Phase 3: Targeted Inspection
A. Check Detached Elements
// Find elements with memory but no DOM connection
const getDetached = () => {
const detached = [];
const walker = document.createTreeWalker(
document,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: node => node.isConnected ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT }
);
let node;
while (node = walker.nextNode()) {
detached.push(node);
}
return detached;
};
console.log('Detached elements:', getDetached().slice(0, 20));
B. CSS-Specific Checks
// 1. Count style sheets
console.log('Style sheets:', document.styleSheets.length);
// 2. Find huge style sheets
Array.from(document.styleSheets).forEach(sheet => {
try {
if (sheet.cssRules.length > 1000) {
console.warn(`Large sheet: ${sheet.href || 'inline'} (${sheet.cssRules.length} rules)`);
}
} catch (e) {
// CORS blocked
}
});
// 3. Check for animation leaks
const runningAnimations = [];
document.querySelectorAll('*').forEach(el => {
const style = getComputedStyle(el);
if (style.animationName !== 'none' || style.transitionProperty !== 'none') {
runningAnimations.push(el);
}
});
console.log('Running animations:', runningAnimations.length);
C. Event Listener Audit
// Chrome DevTools command (not in page context!)
// Run in Console: getEventListeners(document)
// Or instrument:
const originalAdd = EventTarget.prototype.addEventListener;
let listenerCount = 0;
EventTarget.prototype.addEventListener = function(type, handler, options) {
listenerCount++;
if (listenerCount % 1000 === 0) {
console.warn(`Total listeners: ${listenerCount}`);
}
return originalAdd.call(this, type, handler, options);
};
📊 Analysis Patterns
Pattern 1: DOM Growth Without Cleanup
📈 DOM node count keeps rising despite navigation
→ Likely: Forgotten modal/overlay, event handler accumulation
→ Fix: Ensure `remove()` called, null references in closures
Pattern 2: CSS Rule Explosion
📈 CSS rules increase on navigation
→ Likely: CSS-in-JS library not cleaning style tags
→ Fix: Check for orphaned `<style>` tags in head/body
Pattern 3: Animation Leaks
🎬 Animations continue on detached elements
→ Likely: Web Animations API or CSS animations not cancelled
→ Fix: `animation.cancel()`, `element.style.animation = 'none'`
Pattern 4: Font/Image Accumulation
🖼️ Fonts or images load repeatedly
→ Likely: Dynamic `@font-face` or `Image()` objects without cleanup
→ Fix: `FontFace` objects need explicit `.load().then(() => document.fonts.delete(font))`
🛠️ Remediation Commands
Force Cleanup Test
// Test if leak is recoverable
investigator.forceGC();
setTimeout(() => {
console.log('After GC - DOM nodes:', document.querySelectorAll('*').length);
console.log('Style sheets:', document.styleSheets.length);
}, 2000);
Bulk Detached Element Removal
// CAUTION: Use only after confirming these are leaks!
const detached = getDetached();
console.log(`Removing ${detached.length} detached elements...`);
detached.forEach(el => el.remove());
Style Sheet Cleanup
// Remove empty/inline style sheets
document.querySelectorAll('style').forEach(style => {
if (!style.textContent.trim() && !style.id) {
style.remove();
}
});
📈 Heuristic Thresholds
| Metric | Warning Threshold | Critical Threshold |
|---|
| DOM nodes | +500 from baseline | +1000 from baseline |
| CSS rules | +200 per navigation | +500 per navigation |
| Detached elements | >50 total | >200 total |
| Memory growth | +10MB without GC | +50MB without GC |
| Long tasks | >200ms average | >500ms single task |
🧪 Validation Checklist
📦 Export & Share
// Save investigation data
const report = investigator.generateReport();
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(report, null, 2));
const downloadLink = document.createElement('a');
downloadLink.href = dataStr;
downloadLink.download = `css-leak-report-${Date.now()}.json`;
downloadLink.click();
⚠️ Important Notes
- Script Impact: This investigator adds ~50-100KB overhead. Remove after testing.
- False Positives: Some frameworks (React, Vue) intentionally keep DOM references.
- Production Caution: Never run this on live user traffic.
- Cross-Browser:
performance.memory only in Chromium. Use Firefox Memory tool instead.
- CORS Issues: Can't read cross-origin stylesheet rules (browser security).
🔗 Further Reading
Remember: The most common CSS-related leaks are:
- Event handlers on detached elements
- CSS animations running on hidden elements
- CSS-in-JS style objects without cleanup
- Web Fonts loaded repeatedly
- Shadow DOM references in closed mode
Happy investigating! 🕵️♂️