← Back to JavaScript, page 9

javascript-0180 · Medium mid

How does a virtual list (windowing) work, and how would you implement the visible range calculation for a fixed row height?

A virtual list renders only the rows near the viewport inside a tall container whose height is the full list size, so the scrollbar behaves normally. On scroll, compute the first and last visible index from scrollTop, viewport height, and row height, add an overscan buffer, and position the rendered rows with padding or transforms. This keeps the DOM small for lists with tens of thousands of items.

Full answer

Rendering 50,000 rows creates 50,000 elements and makes layout, style, and memory usage slow. Windowing renders only what the user can see.

Core idea for fixed row height h, viewport height V, and scrollTop s:

  • start = Math.floor(s / h) and end = Math.ceil((s + V) / h).
  • Add overscan rows above and below (for example 5) to avoid blank areas during fast scrolling, and clamp to [0, count].
  • Total height is count * h. Use a top spacer of start * h and a bottom spacer of (count - end) * h, or absolute positioning with transform: translateY(...). The scrollbar then matches the full list.
  • On scroll, recompute the range. Only re-render when the range changes, and batch the work in requestAnimationFrame. Scroll events are frequent, so make the handler passive and cheap.
  • Reuse DOM nodes where possible (recycling), and use stable keys when a framework renders the rows.

Harder parts for follow-up discussion:

  • Variable row heights: measure rendered rows with ResizeObserver, store heights in an array, keep a prefix-sum array and find the start with binary search, and use an estimated height for unmeasured rows. Scroll position jumps when estimates are corrected, so adjust scrollTop by the difference.
  • Accessibility: screen readers only see rendered rows. Provide aria-rowcount, aria-rowindex, and keyboard navigation that scrolls to the target row. Search in page (Ctrl+F) does not find hidden rows.
  • Scroll anchoring, sticky headers, grids with columns, and horizontal windowing use the same range idea in two dimensions.
  • Libraries exist (react-window, TanStack Virtual), so in a real project, use one and explain the principle in the interview. The CSS property content-visibility: auto skips rendering work for off-screen content with no JavaScript, but the elements remain in the DOM.

Test the pure range function separately from the DOM code, because it holds the logic and edge cases: empty lists, lists shorter than the viewport, and scrolling past the end.

javascript
function visibleRange({ scrollTop, viewportHeight, rowHeight, count, overscan = 3 }) {
  if (count === 0) return { start: 0, end: 0 };
  const maxScroll = Math.max(0, count * rowHeight - viewportHeight);
  const top = Math.min(Math.max(0, scrollTop), maxScroll);
  const first = Math.floor(top / rowHeight);
  const last = Math.ceil((top + viewportHeight) / rowHeight);
  return {
    start: Math.max(0, first - overscan),
    end: Math.min(count, last + overscan),
  };
}

class VirtualList {
  constructor({ container, count, rowHeight, viewportHeight, renderRow, overscan = 3 }) {
    Object.assign(this, { container, count, rowHeight, viewportHeight, renderRow, overscan });
    this.range = { start: -1, end: -1 };
    this.renderCount = 0;
    this.top = document.createElement('div');
    this.body = document.createElement('div');
    this.bottom = document.createElement('div');
    container.append(this.top, this.body, this.bottom);
    container.setAttribute('role', 'list');
    container.setAttribute('aria-rowcount', String(count));
    this.update(0);
  }

  update(scrollTop) {
    const range = visibleRange({
      scrollTop,
      viewportHeight: this.viewportHeight,
      rowHeight: this.rowHeight,
      count: this.count,
      overscan: this.overscan,
    });
    if (range.start === this.range.start && range.end === this.range.end) return false;
    this.range = range;
    this.renderCount++;
    this.top.style.height = range.start * this.rowHeight + 'px';
    this.bottom.style.height = (this.count - range.end) * this.rowHeight + 'px';
    const fragment = document.createDocumentFragment();
    for (let i = range.start; i < range.end; i++) {
      const row = this.renderRow(i);
      row.style.height = this.rowHeight + 'px';
      row.setAttribute('aria-rowindex', String(i + 1));
      fragment.append(row);
    }
    this.body.replaceChildren(fragment);
    return true;
  }
}

const container = document.createElement('div');
document.body.append(container);
const list = new VirtualList({
  container,
  count: 50000,
  rowHeight: 30,
  viewportHeight: 300,
  renderRow: (i) => Object.assign(document.createElement('div'), { textContent: 'Row ' + i, role: 'listitem' }),
});

const summary = () => {
  const rows = list.body.children;
  const total = parseInt(list.top.style.height) + rows.length * 30 + parseInt(list.bottom.style.height);
  return `rows ${rows[0].textContent} to ${rows[rows.length - 1].textContent}, ${rows.length} nodes, total height ${total}`;
};

console.log('start:', summary());
console.log('scroll 1 px re-render:', list.update(1), '| scroll 25 px (same range):', list.update(25), '| 200 px:', list.update(200));
console.log('middle:', (list.update(600000), summary()));
console.log('end:', (list.update(10 ** 9), summary()));
console.log('render passes:', list.renderCount, '| DOM nodes in the page:', document.querySelectorAll('div').length);

console.log(visibleRange({ scrollTop: 0, viewportHeight: 100, rowHeight: 20, count: 0 }));
console.log(visibleRange({ scrollTop: 0, viewportHeight: 300, rowHeight: 20, count: 4 }));
console.log(visibleRange({ scrollTop: 50, viewportHeight: 100, rowHeight: 20, count: 100, overscan: 0 }));

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: start: rows Row 0 to Row 12, 13 nodes, total height 1500000 scroll 1 px re-render: true | scroll 25 px (same range): false | 200 px: true middle: rows Row 19997 to Row 20012, 16 nodes, total height 1500000 end: rows Row 49987 to Row 49999, 13 nodes, total height 1500000 render passes: 5 | DOM nodes in the page: 17 { start: 0, end: 0 } { start: 0, end: 4 } { start: 2, end: 8 }

Key points

  • Render only visible rows plus overscan inside a container with the full height.
  • start = floor(scrollTop / h), end = ceil((scrollTop + viewport) / h), clamped.
  • Use spacers or transforms so the scrollbar matches the full list.
  • Update only when the range changes, scheduled with requestAnimationFrame.
  • Variable heights need measurement, prefix sums, and binary search; accessibility needs aria row attributes.

Common mistakes

  • Rendering the whole list and hoping the browser handles it.
  • Omitting the overscan, which shows blank rows when scrolling fast.
  • Rebuilding the rows on every scroll event even when the range did not change.
  • Forgetting accessibility attributes and keyboard support for hidden rows.

Follow-ups

  • How would you support rows with different heights?
  • How would you keep the scroll position when items are added at the top?
  • When is content-visibility auto enough?

Tips

  • Give the formula and the clamp first, then the DOM structure.
  • Mention that Ctrl+F and screen readers only see rendered rows.
  • Say that in production you would use a tested library.