Variable-Height Item Virtualization
What you'll learn: How to build virtual scrollers that work with items of different, dynamically measured heights.
In fixed-height virtualization, every item has the same size, making calculations straightforward. But real-world content—social media posts, comments, product cards—often varies wildly in height. Variable-height virtualization requires measuring each rendered item and maintaining a position map so you can accurately calculate scroll positions and visible ranges.
The Core Challenge
Think of it like organizing a bookshelf where each book has a different thickness. You can't just multiply "number of books × average thickness" to find where book #47 sits. You need to measure and track each book's actual thickness.
When virtualizing variable-height items:
- Render initial items in the viewport
- Measure their actual heights after rendering using
getBoundingClientRect()oroffsetHeight - Store these measurements in an array or map
- Calculate cumulative positions (item 0 at 0px, item 1 at 0+height₀, item 2 at 0+height₀+height₁, etc.)
- Update calculations when scrolling to determine which items should be visible based on scroll position
- Re-measure when content changes (like images loading or text expanding)
Dynamic Updates
The tricky part? Content can change size after initial render—images load, fonts swap, text wraps differently. You need to observe size changes (using ResizeObserver or manual checks) and recalculate positions when items grow or shrink.
This creates more complexity than fixed-height virtualization, but it's essential for dynamic content while maintaining smooth performance with thousands of items.
Key Takeaway: Variable-height virtualization requires measuring rendered items and maintaining a dynamic position map that updates as content loads and changes size, trading some complexity for flexibility with real-world variable content.