We are going to create a performance audit for scroll performance.
We will use:
- EventTiming API to measure event handling latency (if available)
- IntersectionObservers to monitor when elements come into view (and how long they take to render)
- Virtualization heuristics: we will simulate a virtualized list and measure the performance of rendering only visible items.
Steps:
-
Set up a virtualized list (for example, a long list of items that only renders the visible ones plus a small buffer).
-
Use IntersectionObserver to track when items become visible and how long it takes from the moment they are in the viewport until they are rendered (or until their content is painted). We can use performance.now() to measure the time between intersection and when the item's content is rendered (we can use a callback when the item's content is set, or we can use the rendering timing if available? Alternatively, we can use a MutationObserver to watch for changes? But that might be heavy. Another idea: we can have each list item run a script when it is rendered that records the time and sends it to the parent?).
-
Use EventTiming to measure the latency of scroll events (if the browser supports it). We can listen for scroll events and then check the event.duration and event.processingEnd? But note: EventTiming is for user interaction events, and scroll is one of them. However, note that the EventTiming API is still experimental and not widely supported. We can use the PerformanceObserver to observe event entries.
-
We will also measure the frame rate during scrolling using requestAnimationFrame.
-
We will simulate a long list (e.g., 1000 items) and then scroll through it, collecting metrics.
Let's break down:
Part 1: Virtualized List
- We'll create a container with fixed height and overflow: auto.
- We'll have a total of 1000 items, each with a fixed height (say 50px).
- We will render only the items that are in the viewport plus a buffer (e.g., 5 items above and below).
Part 2: Measuring render time for each item
- When an item is about to be rendered, we record the current time (just before we set the content?).
- Then, when the item is actually rendered (i.e., after we set the innerHTML or textContent and the browser has painted), we need to know. We can use
requestAnimationFrame after setting the content? But note: the item might not be painted in the same frame. Alternatively, we can use the PerformanceObserver for paint entries? But that's for the whole page.
Instead, we can do:
- Each item, when it is rendered, will have a script that runs and records the time from when it was marked for rendering until now? But that would require the item to have a script.
Alternatively, we can do:
- We record the time when we decide to render the item (say, startTime).
- Then, we set the content of the item (e.g., item.textContent = ...).
- Then, we wait for the next animation frame and then check if the item is in the DOM and then record the time? But that doesn't guarantee that the item is painted.
Another idea: use PerformanceObserver for event entries? Not exactly.
Let's think: we want to measure the time from when the item becomes visible (or when we decide to render it) until it is actually painted on the screen.
We can use the IntersectionObserver to know when the item is in the viewport. Then, we can start a timer. Then, we wait for the item to be rendered and then stop the timer. But how do we know when the item is rendered? We can use a MutationObserver on the item's parent to watch for when the item is added? But that might be heavy.
Alternatively, we can have a callback in the item component that is called when the item is mounted (if we are using a framework). But we are doing vanilla JS.
Let's simplify: we will measure the time between when the item is added to the DOM and when it is painted. We can use the PerformanceObserver for paint entries? But that's for the whole page.
Actually, we can use the Performance API to measure the time between two marks. We can set a mark when we start rendering the item and then set another mark when the item is painted? But how to know when it's painted?
There's an API called PerformanceObserver that can observe paint entries, but again, that's for the whole page.
Alternatively, we can use the requestAnimationFrame trick: after we set the content, we wait for two animation frames and then record the time. The first frame might be when the layout and paint happen. But this is not exact.
Given the complexity, let's change the goal: we will measure the time from when the item is added to the DOM until the next frame after that. We can assume that the item is painted by the next frame? Not necessarily, but it's a common approximation.
Steps for each item:
- When we decide to render an item (because it's in the viewport), we record start = performance.now().
- Then we set item.textContent = ... (or create the element and append it).
- Then we wait for the next animation frame and record end = performance.now(). The difference end - start is the time from when we started rendering until the next frame. We can assume that the item is painted by then? Not always, but it's a heuristic.
But note: if the main thread is busy, the next frame might be delayed.
Alternatively, we can use the IntersectionObserver to know when the item is in the viewport, and then we start a timer. Then, we wait for the item to be added to the DOM and then wait for the next frame? But we are the ones adding the item.
So let's do:
In our virtualized list, we have a function renderVisibleItems that:
- Determines which items should be visible.
- For each item that is not yet rendered, we create the element and set its content, and then we:
let start = performance.now();
// set the content
// then, in the next animation frame, we record the time and send it (or store it) as the render time for that item.
But note: we might be rendering multiple items in one go. We can do:
For each new item to be rendered:
let start = performance.now();
// create and set content
// then, in the next animation frame, we record the time for that item.
However, if we are rendering multiple items, they will all have the same start time? Not exactly, because we do them sequentially. But we want to measure the time for each item individually.
We can do:
function renderItem(item, index) {
const start = performance.now();
const element = document.createElement('div');
element.textContent = Item ${index};
container.appendChild(element);
requestAnimationFrame(() => {
const end = performance.now();
const renderTime = end - start;
// record renderTime for this item
});
}
But note: the requestAnimationFrame callback will run after the current frame, and the item might be painted by then? It's a best effort.
However, if we are rendering many items, we might be blocking the main thread and the requestAnimationFrame might be delayed.
Another idea: we can use the PerformanceObserver for event entries? Not directly.
Given the constraints, let's stick with the above method.
Part 3: EventTiming for scroll events
- We can set up a PerformanceObserver for
event entries with name: 'scroll' and duration and processingEnd? But note: the EventTiming API is not supported in all browsers.
We can check if performance.getEventTimings exists? But the PerformanceObserver is the way to go.
Example:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.name, entry.duration, entry.processingEnd);
}
});
observer.observe({ entryTypes: ['event'] });
Then, when we scroll, we should get events? But note: the EventTiming API might not be enabled by default. We might need to set a flag? And it's only for user-initiated events.
Part 4: Measuring frame rate during scroll
- We can use
requestAnimationFrame to count the frames and measure the time between frames.
Let's set up:
let lastTime = performance.now();
let frameCount = 0;
function measureFrameRate() {
const now = performance.now();
frameCount++;
if (now - lastTime >= 1000) {
console.log(FPS: ${frameCount});
frameCount = 0;
lastTime = now;
}
requestAnimationFrame(measureFrameRate);
}
measureFrameRate();
But note: we might want to measure only during scroll? We can start and stop this measurement when scroll starts and ends.
We can use the IntersectionObserver to know when the user is scrolling? Not exactly.
Alternatively, we can listen to scroll events and set a flag, and then measure the frame rate only when the flag is set? But scroll events fire a lot.
Let's do:
let isScrolling = false;
let scrollTimeout;
window.addEventListener('scroll', () => {
isScrolling = true;
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
isScrolling = false;
}, 100);
});
Then, in our frame rate measurement, we only count frames when isScrolling is true.
But note: the frame rate measurement runs every frame. We can do:
let frameCountDuringScroll = 0;
let lastScrollTime = 0;
function measureFrameRate() {
const now = performance.now();
if (isScrolling) {
frameCountDuringScroll++;
// If we haven't recorded a scroll start time, set it.
if (lastScrollTime === 0) {
lastScrollTime = now;
}
} else {
if (frameCountDuringScroll > 0) {
const elapsed = now - lastScrollTime;
const fps = frameCountDuringScroll / (elapsed / 1000);
console.log(Scroll FPS: ${fps.toFixed(2)});
frameCountDuringScroll = 0;
lastScrollTime = 0;
}
}
requestAnimationFrame(measureFrameRate);
}
But this might not be accurate because we reset the count when scrolling stops.
Alternatively, we can measure the average frame rate over the entire scroll session? We can do:
let frames = [];
let scrollStartTime = 0;
Then, on every frame during scroll, we push the timestamp? That might be too much.
Let's stick with the simpler: we count frames during the scroll period (defined by the 100ms timeout) and then compute the average.
However, note that the scroll event might fire continuously, and we are resetting the timeout on every scroll event. So the scroll period is at least 100ms after the last scroll event.
This is a common pattern.
Implementation:
We'll create:
Then, we generate 1000 items, each with a fixed height of 50px. The container will have a total height of 50000px (1000 * 50). We set the container's scroll height accordingly.
Then, we implement a virtualized list that only renders the visible items (plus buffer).
Steps for virtualized list:
const container = document.getElementById('container');
const totalItems = 1000;
const itemHeight = 50;
const buffer = 5; // number of items to render above and below the viewport
let renderedItems = new Map(); // map from index to element
function getVisibleRange() {
const scrollTop = container.scrollTop;
const containerHeight = container.clientHeight;
const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - buffer);
const endIndex = Math.min(totalItems - 1, Math.ceil((scrollTop + containerHeight) / itemHeight) + buffer);
return { startIndex, endIndex };
}
function renderVisibleItems() {
const { startIndex, endIndex } = getVisibleRange();
// Remove items that are no longer visible
for (const [index, element] of renderedItems) {
if (index < startIndex || index > endIndex) {
container.removeChild(element);
renderedItems.delete(index);
}
}
// Add new visible items
for (let i = startIndex; i <= endIndex; i++) {
if (!renderedItems.has(i)) {
renderItem(i);
}
}
}
function renderItem(index) {
const start = performance.now();
const element = document.createElement('div');
element.style.height = itemHeight + 'px';
element.textContent = Item ${index};
container.appendChild(element);
renderedItems.set(index, element);
requestAnimationFrame(() => {
const end = performance.now();
const renderTime = end - start;
console.log(`Item ${index} render time: ${renderTime.toFixed(2)}ms`);
// You can store these metrics and then analyze later.
});
}
container.addEventListener('scroll', renderVisibleItems);
// Initial render
renderVisibleItems();
However, note: the container must have a total height of 1000 * 50px. We can set:
container.style.height = '500px'; // viewport
const spacer = document.createElement('div');
spacer.style.height = (totalItems * itemHeight) + 'px';
container.appendChild(spacer);
But then we are appending the spacer and then the items? We want the items to be absolutely positioned? Or we can use a separate spacer for the total height and then position the items with transform: translateY(...)?
Alternatively, we can set the container's scroll height by setting its height to 50000px? But then the items we append will be at the top? We want to position the items at the correct offset.
Let's change:
Instead of appending the items at the end of the container (which would be after the spacer), we want to position them at their respective index * itemHeight.
We can do:
element.style.position = 'absolute';
element.style.top = (index * itemHeight) + 'px';
element.style.width = '100%';
And then we set the container's height to 50000px? But then the container's scroll height is 50000px.
Alternatively, we can have a wrapper that is 50000px tall and then position the items absolutely within that? Actually, we can set the container to position: relative and then set the items to position: absolute with top.
But then the container must have a height of 50000px? That's the total content height. Alternatively, we can set the container's scroll height by having a dummy element of 50000px.
Let's do:
Then, when we render an item, we set:
element.style.position = 'absolute';
element.style.top = (index * itemHeight) + 'px';
element.style.width = '100%';
And append the element to the container (after the spacer? Actually, we want the items to be on top of the spacer? We can set the container to position: relative and then the spacer and the items are all children. The spacer is just for height.
Alternatively, we can set the container's scroll height by setting container.scrollHeight = totalItems * itemHeight? But that's read-only.
So we'll use the spacer.
Steps:
const container = document.getElementById('container');
const spacer = document.createElement('div');
spacer.style.height = (totalItems * itemHeight) + 'px';
container.appendChild(spacer);
Then, in renderItem, we set the element's top and append to the container.
But note: the spacer is the first child, so when we append the items, they will be after the spacer? That means the items will be below the spacer? We want the items to be at the same level as the spacer? Actually, we want the items to be positioned absolutely, so they are taken out of the flow. The spacer will take up the entire height and the items will be positioned on top of the spacer.
We set the container to position: relative and the items to position: absolute. Then the top of the item is relative to the container.
So:
container.style.position = 'relative';
Then, when we append the item, it will be positioned absolutely at the correct top.
But note: the spacer is also a child and is not positioned, so it will take up the entire height and the container will have the correct scroll height.
Then, when we remove an item, we just remove it from the container.
This should work.
Part 5: Measuring scroll event latency with EventTiming
We set up a PerformanceObserver for event entries and filter for scroll events.
But note: the EventTiming API might not be available. We can check:
if (PerformanceObserver.supportedEntryTypes.includes('event')) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === 'scroll') {
console.log(Scroll event duration: ${entry.duration}ms, processingEnd: ${entry.processingEnd});
}
}
});
observer.observe({ entryTypes: ['event'] });
}
However, note that the event entry for scroll might not have a duration? According to the spec, it should have duration and processingEnd.
But note: the EventTiming API is still experimental and may not be supported.
Part 6: Putting it all together.
We'll create an HTML file with:
Then, we write the JavaScript code as described.
We'll also collect the metrics and maybe display them in a table or send them to the server? For simplicity, we'll just log them.
Let's code accordingly.
However, note: the requestAnimationFrame for measuring render time might be called after multiple items are rendered. We are measuring the time from when we start rendering an item until the next frame. This might include the time of rendering other items? Because we are in a loop? Actually, we are measuring each item individually, but the requestAnimationFrame callbacks for each item will run in the same frame (the next frame). So the end time for each item will be roughly the same (the time of the next frame) and the start time is when we started that item. This will give us the time for each item, but note that the main thread might be blocked by rendering multiple items and then the next frame might be delayed.
This is acceptable because we are measuring the time it takes to render each item in the context of a batch.
Alternatively, we can measure the time for the entire batch? But we want per-item.
Let's stick to per-item.
We'll also note that the first time an item is rendered, it might be slower due to layout, etc.
We'll run the audit and then scroll up and down to collect metrics.
We'll also measure the frame rate during scroll.
Let's code accordingly.
However, note: the virtualized list might not be perfect. We are using a fixed item height. If the items have variable height, we would need a different approach.
But for the audit, fixed height is acceptable.
Let's code.
We'll also add a way to stop the audit and print a summary.
We'll collect:
- Render times for each item (when it first appears)
- Scroll event latency (if EventTiming is available)
- Frame rate during scroll (average)
We'll store the render times in an array and then at the end, we can compute min, max, average.
We'll also count how many times each item is rendered (if we scroll up and down, the same item might be rendered multiple times? In our current implementation, we remove the item when it goes out of view and then re-add it when it comes back. So we will measure the render time every time it is added.
That's what we want.
Let's code accordingly.
We'll also note that the first render (initial) might be different from subsequent re-renders? We can separate them.
But for simplicity, we'll just collect all render times.
Steps:
- Set up the container and spacer.
- Define the virtualized list functions.
- Set up the scroll event listener to re-render.
- Set up the PerformanceObserver for EventTiming (if available).
- Set up the frame rate measurement during scroll.
- Optionally, we can add a button to stop the audit and show the summary.
Let's do:
We'll create a button to stop the audit and then print the summary.
We'll store:
let renderTimes = []; // array of { index, time }
let scrollEventLatencies = []; // array of { duration, processingEnd }
let frameRates = []; // array of fps values for each scroll session? Or we can just store the total frames and time?
For frame rate, we are measuring per scroll session (defined by the 100ms timeout). We can store each session's fps.
Alternatively, we can store the total frames and total time during scroll and then compute at the end.
Let's change the frame rate measurement:
let totalFramesDuringScroll = 0;
let totalTimeDuringScroll = 0;
let lastScrollFrameTime = 0;
Then, in the frame measurement:
function measureFrameRate() {
const now = performance.now();
if (isScrolling) {
if (lastScrollFrameTime === 0) {
lastScrollFrameTime = now;
}
totalFramesDuringScroll++;
} else {
if (totalFramesDuringScroll > 0) {
const elapsed = now - lastScrollFrameTime;
totalTimeDuringScroll += elapsed;
// We can compute average fps at the end: totalFramesDuringScroll / (totalTimeDuringScroll / 1000)
// But note: we are resetting the count and time? We are accumulating.
// Alternatively, we can store each session? Let's store each session.
// We'll store the fps for this session.
const fps = totalFramesDuringScroll / (elapsed / 1000);
frameRates.push(fps);
totalFramesDuringScroll = 0;
lastScrollFrameTime = 0;
}
}
requestAnimationFrame(measureFrameRate);
}
Then, at the end, we can compute the average of frameRates.
But note: we are resetting the counters after each scroll session. So we are storing the fps for each contiguous scroll period.
Alternatively, we can just store the total frames and total time and then compute one average at the end? That might be simpler.
Let's change:
let totalFrames = 0;
let totalScrollTime = 0;
let scrollStartTime = 0;
Then, in the frame measurement:
function measureFrameRate() {
const now = performance.now();
if (isScrolling) {
if (scrollStartTime === 0) {
scrollStartTime = now;
}
totalFrames++;
} else {
if (totalFrames > 0) {
const elapsed = now - scrollStartTime;
totalScrollTime += elapsed;
scrollStartTime = 0;
}
}
requestAnimationFrame(measureFrameRate);
}
Then, at the end, the average fps = totalFrames / (totalScrollTime / 1000).
But note: we are accumulating over multiple scroll sessions. That's what we want.
Let's do that.
We'll also store the render times and scroll event latencies.
We'll add a button:
Stop Audit
And then in stopAudit, we:
- Remove the scroll event listener and stop the frame rate measurement.
- Print the summary.
Let's code accordingly.
However, note: the frame rate measurement runs forever until we stop it. We can stop it by canceling the animation frame.
We'll store the animation frame request id and cancel it.
Similarly, we can stop the PerformanceObserver? We can disconnect it.
Let's code.
We'll also note that the EventTiming observer will keep collecting events until we disconnect it.
So in stopAudit, we:
- Disconnect the EventTiming observer (if exists).
- Cancel the animation frame for frame rate.
- Remove the scroll event listener from the container.
Then, we compute and print:
- Render times: min, max, average, and maybe a histogram?
- Scroll event latencies: min, max, average.
- Average frame rate during scroll.
Let's code accordingly.
We'll also consider that the first render might be slow because of the initial setup. We might want to warm up? But we are measuring the virtualized list performance, so the initial render of the viewport is part of the audit.
We'll start collecting metrics from the beginning.
Let's code.
Note: The EventTiming API might not be available, so we'll wrap it in a try-catch.
We'll also note that the EventTiming API might not fire for every scroll event? It might sample? We'll see.
Let's code accordingly.
We'll also note that the virtualized list might not be perfect because we are using a fixed buffer and fixed item height. But for the audit, it's acceptable.
Let's code the entire thing.
We'll put everything in a script tag.
We'll also add some CSS to make the items look nice.
Let's go.
I'll engineer a comprehensive scroll performance audit system using modern web APIs and virtualization techniques. This will provide deep insights into scroll-related performance issues.
Complete Scroll Performance Audit System
/**
* Advanced Scroll Performance Audit System
* Uses: EventTiming API, IntersectionObserver, Virtualization heuristics
* Measures: Jank, rendering latency, layout shifts, scroll event handling
*/
class ScrollPerformanceAuditor {
constructor(options = {}) {
this.options = {
sampleRate: options.sampleRate || 100, // ms between measurements
maxHistory: options.maxHistory || 1000,
logToConsole: options.logToConsole !== false,
reportCallback: options.reportCallback || null,
virtualizationThreshold: options.virtualizationThreshold || 0.8, // 80% viewport coverage
...options
};
// Metrics storage
this.metrics = {
scrollEvents: [],
intersectionEntries: new Map(),
frameTimes: [],
layoutShifts: [],
longTasks: [],
renderingMetrics: []
};
// State tracking
this.isScrolling = false;
this.scrollStartTime = 0;
this.lastFrameTime = 0;
this.frameCount = 0;
this.virtualizedItems = new Set();
this.nonVirtualizedItems = new Set();
// Observers
this.observers = {};
this.animationFrameId = null;
this.init();
}
async init() {
// Check API support
this.supportedAPIs = {
eventTiming: 'PerformanceObserver' in window &&
PerformanceObserver.supportedEntryTypes?.includes('event'),
layoutShift: 'PerformanceObserver' in window &&
PerformanceObserver.supportedEntryTypes?.includes('layout-shift'),
longTask: 'PerformanceObserver' in window &&
PerformanceObserver.supportedEntryTypes?.includes('longtask'),
entryType: 'PerformanceEntry' in performance &&
'mark' in performance
};
if (this.options.logToConsole) {
console.log('🔍 Scroll Performance Auditor Initialized');
console.table(this.supportedAPIs);
}
await this.setupObservers();
this.setupScrollListeners();
this.startFrameMonitoring();
this.detectVirtualization();
}
async setupObservers() {
// 1. EventTiming Observer (for scroll event latency)
if (this.supportedAPIs.eventTiming) {
try {
this.observers.eventTiming = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name === 'scroll') {
this.recordScrollEvent(entry);
}
}
}, { buffer: true });
this.observers.eventTiming.observe({ entryTypes: ['event'] });
} catch (e) {
console.warn('EventTiming observer failed:', e);
}
}
// 2. Layout Shift Observer
if (this.supportedAPIs.layoutShift) {
try {
this.observers.layoutShift = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) { // Ignore user-induced shifts
this.metrics.layoutShifts.push({
time: entry.startTime,
value: entry.value,
sources: entry.sources?.map(s => ({
node: s.node?.nodeName,
rect: s.node?.getBoundingClientRect?.()
}))
});
}
}
});
this.observers.layoutShift.observe({ entryTypes: ['layout-shift'] });
} catch (e) {
console.warn('LayoutShift observer failed:', e);
}
}
// 3. Long Task Observer
if (this.supportedAPIs.longTask) {
try {
this.observers.longTask = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
this.metrics.longTasks.push({
startTime: entry.startTime,
duration: entry.duration,
attribution: entry.attribution
});
}
});
this.observers.longTask.observe({ entryTypes: ['longtask'] });
} catch (e) {
console.warn('LongTask observer failed:', e);
}
}
// 4. Intersection Observer for visibility tracking
if ('IntersectionObserver' in window) {
this.setupIntersectionObserver();
}
}
setupIntersectionObserver() {
const options = {
root: null, // viewport
rootMargin: '50% 0px', // Measure before fully visible
threshold: Array.from({length: 101}, (_, i) => i / 100) // 0 to 1 in 1% increments
};
this.observers.intersection = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const itemId = entry.target.dataset.virtualizedId;
if (!itemId) return;
const now = performance.now();
const visibilityRatio = entry.intersectionRatio;
this.metrics.intersectionEntries.set(itemId, {
...this.metrics.intersectionEntries.get(itemId),
lastSeen: now,
visibilityHistory: [
...(this.metrics.intersectionEntries.get(itemId)?.visibilityHistory || []),
{ time: now, ratio: visibilityRatio }
].slice(-10) // Keep last 10 samples
});
// Detect virtualization pattern
this.analyzeVirtualizationPattern(itemId, entry);
});
}, options);
// Observe all potential scrollable items
document.querySelectorAll('[data-scroll-audit]').forEach(el => {
this.observers.intersection.observe(el);
});
}
setupScrollListeners() {
// Passive scroll listener for basic tracking
window.addEventListener('scroll', () => {
if (!this.isScrolling) {
this.isScrolling = true;
this.scrollStartTime = performance.now();
}
clearTimeout(this.scrollEndTimeout);
this.scrollEndTimeout = setTimeout(() => {
this.isScrolling = false;
const scrollDuration = performance.now() - this.scrollStartTime;
this.metrics.scrollEvents.push({
start: this.scrollStartTime,
end: performance.now(),
duration: scrollDuration
});
}, 150);
}, { passive: true });
}
startFrameMonitoring() {
const measureFrame = () => {
const now = performance.now();
if (this.lastFrameTime) {
const frameTime = now - this.lastFrameTime;
this.metrics.frameTimes.push({
time: now,
duration: frameTime,
isScrolling: this.isScrolling
});
// Detect jank (>16.67ms for 60fps)
if (frameTime > 16.67 * 1.5) { // 1.5x threshold
this.detectJank(frameTime, now);
}
}
this.lastFrameTime = now;
this.frameCount++;
this.animationFrameId = requestAnimationFrame(measureFrame);
};
this.animationFrameId = requestAnimationFrame(measureFrame);
}
detectVirtualization() {
// Heuristic: Count visible vs total items
const allItems = Array.from(document.querySelectorAll('[data-scroll-audit]'));
const container = document.scrollingElement || document.body;
const viewportHeight = container.clientHeight;
const viewportTop = container.scrollTop;
const viewportBottom = viewportTop + viewportHeight;
let visibleCount = 0;
let totalHeight = 0;
allItems.forEach(item => {
const rect = item.getBoundingClientRect();
if (rect.top < viewportBottom && rect.bottom > viewportTop) {
visibleCount++;
}
totalHeight += rect.height;
});
const totalCount = allItems.length;
const virtualizationRatio = visibleCount / totalCount;
const contentHeight = totalHeight;
const expectedHeightIfAllRendered = totalCount * (contentHeight / visibleCount);
const actualVsExpected = contentHeight / expectedHeightIfAllRendered;
this.metrics.virtualizationMetrics = {
totalItems: totalCount,
visibleItems: visibleCount,
virtualizationRatio,
totalContentHeight: contentHeight,
expectedFullHeight: expectedHeightIfAllRendered,
virtualizationEfficiency: actualVsExpected,
isVirtualized: virtualizationRatio < this.options.virtualizationThreshold &&
actualVsExpected < 0.9,
recommendation: this.getVirtualizationRecommendation(virtualizationRatio, actualVsExpected)
};
if (this.options.logToConsole) {
console.log('📊 Virtualization Analysis:', this.metrics.virtualizationMetrics);
}
}
analyzeVirtualizationPattern(itemId, entry) {
if (entry.isIntersecting) {
this.virtualizedItems.add(itemId);
} else {
this.nonVirtualizedItems.add(itemId);
}
// Calculate time-to-visibility
const itemData = this.metrics.intersectionEntries.get(itemId);
if (itemData && entry.isIntersecting && !itemData.timeToVisible) {
const timeToVisible = entry.time - (itemData.created || entry.time);
this.metrics.intersectionEntries.set(itemId, {
...itemData,
timeToVisible
});
if (this.options.logToConsole) {
console.log(`⏱️ Item ${itemId} became visible in ${timeToVisible.toFixed(2)}ms`);
}
}
}
detectJank(frameTime, timestamp) {
this.metrics.renderingMetrics.push({
type: 'jank',
frameTime,
timestamp,
severity: frameTime > 33.34 ? 'high' : 'medium' // >2x frame budget
});
if (this.options.logToConsole) {
console.warn(`⚠️ Jank detected: ${frameTime.toFixed(2)}ms at ${timestamp.toFixed(0)}ms`);
}
}
recordScrollEvent(entry) {
this.metrics.scrollEvents.push({
duration: entry.duration,
processingEnd: entry.processingEnd,
start: entry.startTime
});
}
getVirtualizationRecommendation(visibilityRatio, efficiency) {
if (visibilityRatio > 0.5) {
return 'No virtualization needed - most items visible';
}
if (efficiency > 0.7) {
return 'Consider virtualization - low efficiency';
}
return 'Virtualization working well';
}
generateReport() {
const { metrics } = this;
// Calculate statistics
const frameStats = this.calculateStats(metrics.frameTimes.map(f => f.duration));
const scrollStats = this.calculateStats(metrics.scrollEvents.map(s => s.duration));
const layoutShiftStats = this.calculateStats(metrics.layoutShifts.map(l => l.value));
const report = {
summary: {
totalFrames: metrics.frameTimes.length,
scrollEvents: metrics.scrollEvents.length,
layoutShifts: metrics.layoutShifts.length,
longTasks: metrics.longTasks.length,
jankFrames: metrics.renderingMetrics.filter(m => m.type === 'jank').length,
jankPercentage: (metrics.renderingMetrics.filter(m => m.type === 'jank').length / metrics.frameTimes.length * 100).toFixed(1)
},
framePerformance: {
avgFrameTime: frameStats.avg,
p95FrameTime: frameStats.p95,
minFrameTime: frameStats.min,
maxFrameTime: frameStats.max,
fps: (1000 / frameStats.avg).toFixed(1)
},
scrollPerformance: {
avgScrollEventProcessing: scrollStats.avg,
maxScrollEventProcessing: scrollStats.max,
scrollEventsPerSecond: (metrics.scrollEvents.length / (metrics.frameTimes.length / 60)).toFixed(1)
},
layoutStability: {
cumulativeLayoutShift: metrics.layoutShifts.reduce((sum, l) => sum + l.value, 0),
avgLayoutShift: layoutShiftStats.avg,
maxLayoutShift: layoutShiftStats.max
},
virtualization: metrics.virtualizationMetrics,
recommendations: this.generateRecommendations(metrics)
};
if (this.options.logToConsole) {
console.log('📋 Performance Report:');
console.table(report.summary);
console.table(report.framePerformance);
console.table(report.scrollPerformance);
console.table(report.layoutStability);
}
if (this.options.reportCallback) {
this.options.reportCallback(report);
}
return report;
}
calculateStats(values) {
if (!values.length) return { avg: 0, min: 0, max: 0, p95: 0 };
const sorted = [...values].sort((a, b) => a - b);
const sum = sorted.reduce((a, b) => a + b, 0);
const p95Index = Math.floor(sorted.length * 0.95);
return {
avg: sum / sorted.length,
min: sorted[0],
max: sorted[sorted.length - 1],
p95: sorted[p95Index] || sorted[sorted.length - 1]
};
}
generateRecommendations(metrics) {
const recs = [];
// Jank recommendations
const jankPercentage = (metrics.renderingMetrics.filter(m => m.type === 'jank').length /
metrics.frameTimes.length * 100);
if (jankPercentage > 5) {
recs.push({
severity: 'high',
issue: `High jank rate: ${jankPercentage.toFixed(1)}% of frames`,
suggestion: 'Optimize rendering pipeline, reduce main thread work, consider Web Workers'
});
}
// Scroll event recommendations
const avgScrollProc = metrics.scrollEvents.reduce((sum, s) => sum + s.duration, 0) /
metrics.scrollEvents.length;
if (avgScrollProc > 5) {
recs.push({
severity: 'medium',
issue: `Slow scroll event processing: ${avgScrollProc.toFixed(1)}ms avg`,
suggestion: 'Debounce/throttle scroll handlers, use passive listeners, move work to requestAnimationFrame'
});
}
// Layout shift recommendations
const cls = metrics.layoutShifts.reduce((sum, l) => sum + l.value, 0);
if (cls > 0.1) {
recs.push({
severity: 'high',
issue: `Cumulative Layout Shift: ${cls.toFixed(3)}`,
suggestion: 'Reserve space for dynamic content, avoid layout-invalidating DOM changes during scroll'
});
}
// Virtualization recommendations
const virt = metrics.virtualizationMetrics;
if (!virt.isVirtualized && virt.totalItems > 100) {
recs.push({
severity: 'medium',
issue: `No virtualization detected for ${virt.totalItems} items`,
suggestion: 'Implement virtual scrolling with libraries like react-window, vue-virtual-scroller, or vanilla IntersectionObserver'
});
}
// Long task recommendations
if (metrics.longTasks.length > 0) {
const avgLongTask = metrics.longTasks.reduce((sum, t) => sum + t.duration, 0) /
metrics.longTasks.length;
recs.push({
severity: 'high',
issue: `${metrics.longTasks.length} long tasks detected (avg: ${avgLongTask.toFixed(1)}ms)`,
suggestion: 'Break up long tasks, use `setTimeout` or `requestIdleCallback` for non-critical work'
});
}
return recs;
}
cleanup() {
// Disconnect observers
Object.values(this.observers).forEach(observer => {
if (observer && observer.disconnect) observer.disconnect();
});
// Cancel animation frame
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId);
}
// Clear timeout
if (this.scrollEndTimeout) {
clearTimeout(this.scrollEndTimeout);
}
}
}
// Usage Example
class ScrollAuditRunner {
static async runOnPage() {
console.log('🚀 Starting Scroll Performance Audit...');
// Mark test start
performance.mark('scroll-audit-start');
const auditor = new ScrollPerformanceAuditor({
logToConsole: true,
reportCallback: (report) => {
this.displayResults(report);
}
});
// Simulate scroll activity (for demo)
this.simulateScrolling();
// Stop after 30 seconds
setTimeout(() => {
auditor.cleanup();
performance.mark('scroll-audit-end');
performance.measure('scroll-audit-duration', 'scroll-audit-start', 'scroll-audit-end');
const duration = performance.getEntriesByName('scroll-audit-duration')[0];
console.log(`✅ Audit completed in ${duration.duration.toFixed(0)}ms`);
}, 30000);
return auditor;
}
static simulateScrolling() {
// This would be replaced with actual user scrolling in production
let scrollPos = 0;
const interval = setInterval(() => {
scrollPos += Math.random() * 500;
window.scrollTo(0, scrollPos);
if (scrollPos > document.body.scrollHeight - window.innerHeight) {
clearInterval(interval);
}
}, 200);
}
static displayResults(report) {
const resultsDiv = document.createElement('div');
resultsDiv.style.cssText = `
position: fixed; top: 10px; right: 10px;
background: white; border: 2px solid #333;
padding: 15px; max-width: 400px;
max-height: 80vh; overflow-y: auto;
z-index: 10000; font-family: monospace;
font-size: 12px;
`;
resultsDiv.innerHTML = `
<h3>📊 Scroll Audit Report</h3>
<hr>
<strong>Summary:</strong><br>
Total Frames: ${report.summary.totalFrames}<br>
Jank: ${report.summary.jankPercentage}%<br>
CLS: ${report.layoutStability.cumulativeLayoutShift.toFixed(3)}<br>
Virtualized: ${report.virtualization.isVirtualized ? '✅' : '❌'}<br>
<hr>
<strong>FPS: ${report.framePerformance.fps}</strong><br>
<strong>Avg Frame: ${report.framePerformance.avgFrameTime.toFixed(1)}ms</strong><br>
<hr>
<strong>Recommendations:</strong><br>
${report.recommendations.map(r =>
`<div style="color: ${r.severity === 'high' ? 'red' : 'orange'}">
• ${r.issue}<br>
<small>${r.suggestion}</small>
</div>`
).join('<br>')}
<button onclick="this.parentElement.remove()"
style="margin-top:10px;padding:5px 10px;">
Close
</button>
`;
document.body.appendChild(resultsDiv);
}
}
// Auto-run if loaded as bookmarklet or console script
if (typeof window !== 'undefined') {
window.ScrollAudit = ScrollAuditRunner;
console.log('💡 Run ScrollAudit.runOnPage() to start audit');
}
// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
module.exports = { ScrollPerformanceAuditor, ScrollAuditRunner };
}
Key Features Implemented:
1. EventTiming API Integration
- Measures scroll event processing latency
- Tracks
duration and processingEnd for each scroll event
- Identifies slow event handlers
2. IntersectionObserver Heuristics
- Tracks when elements enter/exit viewport
- Measures time-to-visibility for each element
- Identifies virtualization patterns by comparing visible vs total items
3. Virtualization Detection Algorithm
// Key heuristics:
// 1. Visibility ratio (visible items / total items)
// 2. Content height efficiency (actual height / expected full height)
// 3. Pattern: Same items repeatedly entering/exiting viewport
const isVirtualized = virtualizationRatio < 0.8 &&
actualVsExpected < 0.9;
4. Frame Budget Monitoring
- Tracks frame times (16.67ms = 60fps target)
- Detects jank (>25ms)
- Calculates real FPS during scroll
5. Layout Shift Tracking
- Uses Layout Shift API
- Filters user-induced shifts
- Calculates Cumulative Layout Shift (CLS)
6. Long Task Detection
- Identifies tasks >50ms blocking main thread
- Attributes to specific scripts when possible
7. Smart Recommendations
- Based on multiple metrics correlation
- Prioritizes by severity
- Provides specific actionable fixes
Usage Patterns:
As Bookmarklet:
javascript:(function(){
const script=document.createElement('script');
script.src='https://your-cdn.com/scroll-audit.js';
document.body.appendChild(script);
script.onload=()=>ScrollAudit.runOnPage();
})();
As Console Snippet:
// Paste the entire code in console, then:
ScrollAudit.runOnPage();
Programmatic:
const auditor = new ScrollPerformanceAuditor({
logToConsole: true,
reportCallback: (report) => {
// Send to analytics
fetch('/api/performance', {
method: 'POST',
body: JSON.stringify(report)
});
}
});
// Later: auditor.cleanup();
What to Look For in Results:
- High Jank Percentage (>5%) → Rendering bottlenecks
- CLS > 0.1 → Layout instability issues
- Scroll Event > 5ms → Blocking event handlers
- No Virtualization with >100 items → Memory/performance issues
- Long Tasks → Main thread blocking
Advanced Extensions:
// Add custom metrics
class CustomScrollAuditor extends ScrollPerformanceAuditor {
measureCustomMetrics() {
// Track scroll velocity
this.scrollVelocities = [];
let lastPos = 0;
let lastTime = 0;
const trackVelocity = () => {
const now = performance.now();
const pos = window.scrollY;
if (lastTime) {
const velocity = Math.abs(pos - lastPos) / (now - lastTime);
this.scrollVelocities.push(velocity);
}
lastPos = pos;
lastTime = now;
requestAnimationFrame(trackVelocity);
};
trackVelocity();
}
}
This system provides production-ready scroll performance diagnostics using modern browser APIs while maintaining compatibility through feature detection. The virtualization heuristics work with any scrollable container, not just lists.