class ScrollPerformanceAuditor {
constructor(config = {}) {
// Configuration
this.config = {
scrollContainer: document.body,
longTaskThreshold: 50, // ms
virtualizationNodeThreshold: 100,
sampleDuration: 5000, // ms
...config,
};
// State
this.metrics = {
eventTimings: [],
visibilityLag: [],
virtualizationCandidates: [],
};
this.observers = {};
this.knownVisibleElements = new Set();
}
/**
* Initializes all observers and starts the audit.
*/
start() {
if (this.config.sampleDuration) {
setTimeout(() => this.stop(), this.config.sampleDuration);
}
this._initEventTiming();
this._initIntersectionObserver();
this._runVirtualizationHeuristics();
}
/**
* Stops all observers and returns the report.
*/
stop() {
if (this.observers.performance) this.observers.performance.disconnect();
if (this.observers.intersection) this.observers.intersection.disconnect();
return this._generateReport();
}
// ---------------------------------------------------------
// 1. Event Timing (Input Latency)
// ---------------------------------------------------------
_initEventTiming() {
try {
this.observers.performance = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
// Filter for scroll-related interactions
if (['pointerdown', 'pointerup', 'wheel'].includes(entry.name)) {
this.metrics.eventTimings.push({
eventType: entry.name,
// Time from input to start of event handler
inputDelay: entry.processingStart - entry.startTime,
// Time taken by the event handler itself
syncDuration: entry.processingEnd - entry.processingStart,
// Total time from input to browser painting the frame (if available)
presentationTime: entry.duration + entry.startTime,
});
}
});
});
this.observers.performance.observe({ type: 'event', buffered: true });
} catch (e) {
console.warn('Event Timing API not supported', e);
}
}
// ---------------------------------------------------------
// 2. Intersection Observer (Paint Heuristics)
// ---------------------------------------------------------
_initIntersectionObserver() {
this.observers.intersection = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// Mark when the element became visible
if (!entry.target.dataset.auditVisibleTime) {
entry.target.dataset.auditVisibleTime = performance.now();
}
}
});
},
{ root: this.config.scrollContainer, threshold: 0.1 }
);
// Monitor all list-like elements for visibility changes
const potentialLists = document.querySelectorAll('ul, ol, tbody, [role="list"], [data-audit-list]');
potentialLists.forEach((el) => this.observers.intersection.observe(el));
}
// ---------------------------------------------------------
// 3. Virtualization Heuristics
// ---------------------------------------------------------
_runVirtualizationHeuristics() {
// Heuristic: Traverse DOM looking for containers with many direct children
const allContainers = document.querySelectorAll('*');
allContainers.forEach(container => {
const childCount = container.childElementCount;
if (childCount > this.config.virtualizationNodeThreshold) {
// Mark for observation
container.setAttribute('data-audit-list', 'true');
this.observers.intersection.observe(container);
this.metrics.virtualizationCandidates.push({
element: container.tagName,
childCount: childCount,
// We will populate visibleCount later in the report
});
}
});
}
// ---------------------------------------------------------
// Reporting
// ---------------------------------------------------------
_generateReport() {
const eventStats = this._calculateEventStats();
const virtualizationReport = this._assessVirtualization();
return {
summary: {
status: eventStats.avgInputDelay > 50 || eventStats.longTasks > 5 ? 'FAIL' : 'PASS',
score: Math.max(0, 100 - (eventStats.longTasks * 5)),
},
scrollResponsiveness: eventStats,
virtualizationOpportunities: virtualizationReport,
recommendations: this._getRecommendations(eventStats, virtualizationReport),
};
}
_calculateEventStats() {
const delays = this.metrics.eventTimings.map(e => e.inputDelay);
const durations = this.metrics.eventTimings.map(e => e.syncDuration);
const longTasks = durations.filter(d => d > this.config.longTaskThreshold).length;
const sum = arr => arr.reduce((a, b) => a + b, 0);
const avg = arr => (arr.length ? sum(arr) / arr.length : 0);
return {
totalEvents: this.metrics.eventTimings.length,
avgInputDelay: Math.round(avg(delays)),
avgSyncDuration: Math.round(avg(durations)),
longTasksCount: longTasks,
};
}
_assessVirtualization() {
return this.metrics.virtualizationCandidates.map(candidate => {
// Estimate visible items based on scroll height vs container height (rough heuristic)
// or rely on intersection observer data if complex
return {
...candidate,
recommendation: `Virtualization suggested. Reducing DOM nodes from ${candidate.childCount} to ~20 could save ~${Math.round(candidate.childCount * 0.5)}ms layout time.`
};
});
}
_getRecommendations(eventStats, virtReport) {
const recs = [];
if (eventStats.avgInputDelay > 50) {
recs.push('High Input Delay detected. Break up long tasks in scroll handlers using requestIdleCallback or Web Workers.');
}
if (virtReport.length > 0) {
recs.push('Unvirtualized lists detected. Implement windowing (e.g., react-window) to reduce DOM pressure.');
}
return recs;
}
}
// --- Usage Example ---
// 1. Instantiate
const auditor = new ScrollPerformanceAuditor({
virtualizationNodeThreshold: 50, // Flag lists > 50 items
sampleDuration: 10000 // Run for 10 seconds
});
// 2. Start
auditor.start();
// 3. Later (e.g., after user scrolls), get report
setTimeout(() => {
const report = auditor.stop();
console.table(report.scrollResponsiveness);
console.log("Virtualization Opportunities:", report.virtualizationOpportunities);
console.log("Recommendations:", report.recommendations);
}, 11000);