SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Virtualised Lists

Virtual Scrolling

Render only the visible rows of a large list — virtual scrolling keeps DOM node count constant regardless of data size.

Example
const ROW_H = 40, BUFFER = 5;
const $container = $("#list-wrap");
const $inner = $("#list-inner");
const $viewport = $("#list-viewport");
function render() {
  const scrollTop = $viewport.scrollTop();
  const start = Math.max(0, Math.floor(scrollTop / ROW_H) - BUFFER);
  const end   = Math.min(data.length, Math.ceil((scrollTop + $viewport.height()) / ROW_H) + BUFFER);
  $inner.css("paddingTop", start * ROW_H);
  $container.html(data.slice(start, end).map((d, i) =>
    `<div class="row" style="height:${ROW_H}px">${d.name}</div>`).join(""));
}
$viewport.on("scroll", $.throttle(50, render));
$inner.css("height", data.length * ROW_H); render();
Pro Tip

Virtual scrolling makes 100,000-row lists indistinguishable in performance from 50-row lists.