Skip to content

Commit b1f6f19

Browse files
committed
feat(virtual-core): skip sync DOM read in measureElement when cached size exists
1 parent c33902f commit b1f6f19

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

‎packages/virtual-core/src/index.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,21 @@ export const measureElement = <TItemElement extends Element>(
252252
}
253253
}
254254

255+
// When called without a ResizeObserverEntry (sync measurement path),
256+
// return the previously measured size if available. This avoids a
257+
// synchronous layout read (offsetWidth/offsetHeight) on re-renders.
258+
// The ResizeObserver is already observing the element and will deliver
259+
// the accurate size asynchronously if it changed.
260+
// Users who need synchronous DOM reads can provide a custom measureElement.
261+
if (!entry) {
262+
const index = instance.indexFromElement(element)
263+
const key = instance.options.getItemKey(index)
264+
const cachedSize = instance.itemSizeCache.get(key)
265+
if (cachedSize !== undefined) {
266+
return cachedSize
267+
}
268+
}
269+
255270
return (element as unknown as HTMLElement)[
256271
instance.options.horizontal ? 'offsetWidth' : 'offsetHeight'
257272
]
@@ -382,7 +397,7 @@ export class Virtualizer<
382397
// Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].
383398
// null until the first single-lane build; reused (and grown) across rebuilds.
384399
private _flatMeasurements: Float64Array | null = null
385-
private itemSizeCache = new Map<Key, number>()
400+
itemSizeCache = new Map<Key, number>()
386401
private itemSizeCacheVersion = 0
387402
private laneAssignments = new Map<number, number>() // index → lane cache
388403
// Earliest index dirtied since last getMeasurements() rebuild, or null.

0 commit comments

Comments
 (0)