Research: rendering TONS of elements at 60fps #
Goal context: hackermusic is a keyboard-driven player for Subsonic/Navidrome servers. Realistic worst cases: a 10k-track library view, an album grid of ~2k covers, a queue with thousands of rows, instant fuzzy-search filtering of all of it. Findings below, ordered from "free" to "heavy machinery".
0. Principle: fewer DOM nodes first, tricks second #
Every trick below is a mitigation for having too many live DOM nodes. The best render is the one that never happens:
- Render only what can scroll into view (virtualization) or what is near it
(
content-visibility). - Keep rows dead simple: one row = ~4–6 elements (art placeholder, title, artist, duration, maybe a button). Rows built from 30-node component trees kill scroll perf no matter what virtualizer you use.
- Defer richness: render a row skeleton cheaply; hydrate play-count badges, waveform thumbnails, action menus only when visible/idle.
- Paginate server-side (
getAlbumList2/search3are already paged) — the UI should only ever hold what the user has browsed, not the entire DB.
1. Native browser machinery (no dependencies) #
CSS content-visibility: auto — the "native virtualization" #
Skips layout+paint (and rendering subtree work) for off-screen elements while keeping them in the DOM. Measured in the wild: ~15x reduction in forced reflow cost on heavy pages, ~40% less rendering/painting time for offscreen sections.
.track-row,
.album-card {
content-visibility: auto;
contain-intrinsic-size: auto 40px; /* remember last-rendered size */
}
Rules of thumb:
- Apply to self-contained items/blocks, not the scroll container.
- Always pair with
contain-intrinsic-size(auto <estimate>) or the scrollbar jumps / CLS explodes. Theautokeyword lets the browser cache the real size after first render. - Keeps native Ctrl+F, find-in-page, accessibility, and focus order working — things JS virtualization breaks.
- Caveat: DOM nodes stay in memory and layout tree cost still scales with node count. Fine up to roughly 1k–3k items; beyond that use real virtualization (sources agree on this threshold).
- If items are tiny, group them into blocks (e.g. 50–100 rows per block
element) and put
content-visibilityon the blocks to cut management overhead. - Support caveat: it's a Chromium-born feature; feature-detect and fall back to JS virtualization where absent.
CSS containment #
.track-row {
contain: layout style paint;
} /* or contain: content */
Isolates a subtree so layout/paint/style changes inside it can't invalidate
the rest of the page. Cheap, safe on every row. content-visibility: auto
already implies containment; use explicit contain for rows that are always
visible (e.g. the currently-playing row chrome).
contain: layout— internal layout can't affect outside.contain: paint— subtree never paints outside its bounds; also promotes a stacking context.contain: strict(adds size containment) for fixed-size slots like cover art tiles whose size we dictate anyway.
Layer & animation hygiene #
- Animate only
transformandopacity(compositor-only, no layout/paint). Position virtualized items withtransform: translateY()(virtua/tanstack both do this) — nevertop. will-change: transformonly on elements that are actually animating right now, and remove it after — blanketwill-changewastes GPU memory and can make things slower.- Avoid
box-shadow,filter,backdrop-filteron scrollable row content; pre-render effects into images or apply them only to hover/focus states of a single row. contain: paintgives you a compositing boundary for free.
DOM-write discipline #
- Batch writes, then read. Interleaved
element.offsetHeightreads after writes cause layout thrash. In scroll handlers: readscrollToponce (passive listener), compute, then write. - Build subtrees in a
DocumentFragmentand append once when injecting many nodes manually (Solid mostly does the right thing already; this matters for imperative DOM code, e.g. rendering a canvas waveform legend). - Throttle scroll/UI work with
requestAnimationFrame; keep scroll and wheel/touch listeners passive (never callpreventDefaultin them). overscroll-behavior: containon inner scroll panes stops scroll chaining and avoids full-page rubber-band work — great for the multi-pane layout we want.overflow-anchor: noneon virtualized scroll containers (required by virtua) to stop browser scroll-anchoring fights.
Chunked rendering — scheduler.yield() (Chromium 129+) + fallback #
When a huge list must materialize (e.g. user hits "end" in queue, or a filter matches 8k rows), don't render it in one long task. Yield to the browser between chunks so keystrokes/scroll stay at 60fps:
function yieldToMain(): Promise<void> {
if ("scheduler" in window && "yield" in window.scheduler) {
return window.scheduler.yield();
}
// Fallback: MessageChannel beats setTimeout (no 4ms nested-timer clamp)
return new Promise((resolve) => {
const ch = new MessageChannel();
ch.port1.onmessage = () => {
ch.port1.close();
resolve();
};
ch.port2.postMessage(null);
});
}
async function renderChunked<T>(items: T[], renderItem: (t: T) => void) {
for (let i = 0; i < items.length; i += 200) {
items.slice(i, i + 200).forEach(renderItem);
await yieldToMain();
}
}
Media/lazy-loading primitives #
- Cover art:
<img loading="lazy" decoding="async" fetchpriority="low" decoding=async>inside a fixedaspect-ratio: 1container (so layout never shifts when the image lands).decoding="async"keeps decode off the main-thread paint path. <img>for art beats CSSbackground-imagefor lazy-loading and priority hints.- IntersectionObserver (not scroll math): use for "hydrate when near" — attach expensive stuff (EqualizerCanvas, row action buttons, listeners) only when a row enters an expanded root margin; tear down when it leaves.
View Transitions API (same-document) #
For route morphs (artist page → album grid → track list) use
document.startViewTransition() with view-transition-name on only the
few elements that should morph (e.g. the cover art flying from grid tile
to now-playing bar). Snapshots are real work: keep the DOM shallow during
capture, unique names per snapshot (duplicate names skip the transition),
and clear the names after the transition. Compositor-driven, so it's
cheap if you name little.
Audio-adjacent (off the render path entirely) #
Playback must never compete with list rendering:
- Decode/stream in a worker-adjacent setup; serve cached tracks from
OPFS using
createSyncAccessHandle()inside a Web Worker — dramatically faster than IndexedDB for binary blobs and never touches the main thread's event loop. Use IndexedDB (viaidb) for metadata, favorites, config only. - Feed
<audio>/<audio-worklet>viaURL.createObjectURL()from OPFS blobs, or MediaSource; revoke URLs when done. Never data URLs. - Pass buffers across threads with transferables (zero-copy) or
structuredClone; wrap the worker incomlinkfor ergonomics. - Media Session API for OS media keys — keyboard-driven includes hardware keys.
2. Virtualization packages (2026 landscape) #
| Package | Solid support | Size | Notes |
|---|---|---|---|
virtua (virtua/solid) |
first-class (VList, Virtualizer, WindowVirtualizer, experimental VGrid) |
~3 kB gz, tree-shakeable | Zero-config: measures dynamic sizes itself (ResizeObserver), handles reverse/infinite scroll, RTL, scroll restoration, smooth scrollToIndex, DnD, keyboard navigation, sticky. Best feature matrix for a music app. |
| @tanstack/solid-virtual (3.13.x) | headless createVirtualizer / createWindowVirtualizer |
small, headless | Maximum control, great dynamic measurement; you build the markup yourself (pass getters for count/scroll element to stay reactive). Known edge: Suspense interplay. |
| @solid-primitives/virtual (0.2.x) | native Solid (createVirtualList + <VirtualList>) |
tiny | Simplest option: fixed item height, unstyled vertical lists. Track rows are fixed-height — legitimately sufficient and cheapest. |
Decisions from the 2026 comparisons: virtuoso-class batteries-included APIs are React-only; react-window is effectively maintenance-mode (avoid for new projects); TanStack Virtual is the headless standard across frameworks; virtua is the "fast + zero-config, solid adapter" pick and the only one with first-class Solid components plus a grid story (album art grids).
Recommendation for hackermusic:
- Track lists / queue / search results: virtua
VList(or TanStack headless if we want to own the DOM). Track rows are uniform-height, so either is trivially fast; virtua givesscrollToIndexfor the keyboard-driven "jump to playing track" for free. - Album/artist grids: virtua's experimental
VGridor a CSS-Grid + virtualized-columns hybrid. - Under ~1k items (settings panes, playlists): no virtualization at all —
just
content-visibility: autoon sections. - Virtualizing breaks Ctrl+F — fine here: the app has its own keyboard-driven fuzzy search (also faster than find-in-page on a virtualized list).
Integration notes that matter:
- Fixed-height rows (
~40px) +estimateSizeexact ⇒ no measure pass, no scroll jitter. Measure-once cache keyed by track id for any variable-height elements (multi-disc, grouped headers). - Position items with transforms; container gets
overflow-anchor: none. - Scroll-jump on infinite scroll (prepend) is the classic bug — virtua and
TanStack both handle scroll position adjustment; hand-rolled needs
ResizeObserver + manual
scrollTopcompensation. - Keyboard nav is ours to build anyway (that's the product): virtualizers
only need
scrollToIndex({ align })+ keeping focus within the rendered window (focus a sentinel, usetabindex="-1"+focus()on the current row after render — rAF it). overscan(render a few off-screen rows) ≈ 5 is the sweet spot; more hurts, fewer risks white flashes on fast flicks.
3. Solid-specific leverage (we're already ahead) #
Solid's fine-grained reactivity removes most of the reasons these tricks exist in React/Vue apps — no VDOM diffing, updates touch exact text nodes:
- Solid 2.0 unified
<For>(keyed={true} = old For, keyed={false} = old Index). For the queue (reorderable: drag, move, shuffle) use keyed For so DOM nodes move instead of re-rendering. For positionally stable, value-swapping lists (paged search results re-filled in place), non-keyed avoids per-item state churn. Seedocumentation/solid-2.0/03-control-flow.mdin solidjs/solid@next. - No
memoneeded: a row component runs once; per-row signals update independently. The "now playing" highlight should be one shared signal (currentTrackId) that rows read — each row subscribes and only the two affected rows update their class. Never prop-drill anisActiveboolean computed in the parent (that re-renders all rows). batch()around multi-signal updates (e.g. swap tracks: update queue index + time + title atomically, one DOM flush).untrack()inside scroll/worker-callback paths where reactivity is a leak, not a feature.- Component creation cost inside a virtualizer is the remaining hot spot (thousands of closures on filter): virtualizers window this for us; keep row components flat and hoist statics.
createMemothe filtered/sorted list — Solid's memos only recompute on true dependency change, so keystroke-filtering 10k items produces one array memo + the visible window's DOM ops, nothing else. Pair with chunking (§1) or a worker-side index (e.g. minisearch/fuse in a worker) for instant-feeling search.
4. Measurement plan (so the "highly optimized" claim is real) #
- Chrome DevTools Performance traces with 10k synthetic rows: scroll at 60fps, zero long tasks (>50ms) during scroll; INP < 100ms on keypress while a list scrolls.
PerformanceObserverforlongtaskand event latency in dev builds; fail CI perf-test on regressions.- Test the worst case on a throttled CPU (6x) and a Navidrome on a Raspberry Pi — the API is often the slow part, not rendering; caching (§1) is what makes it feel instant.
- Memory check: heap stays flat while scrolling 10k virtualized rows (detach rows properly; watch ResizeObserver leaks).
Quick reference — the actual CSS/JS starter kit #
.pane {
overflow-y: auto;
overscroll-behavior: contain;
contain: strict; /* fixed-size panes we control */
}
.track-row {
contain: layout style paint;
}
.section:not(.track-list) {
content-visibility: auto;
contain-intrinsic-size: auto 300px;
}
.cover {
aspect-ratio: 1;
content-visibility: auto;
contain-intrinsic-size: auto 160px;
}
.cover img {
width: 100%;
height: auto;
}
img[aria-hidden="true"] {
pointer-events: none;
}
.now-playing {
transition: none;
} /* never animate the row chrome */
Key sources #
- web.dev — content-visibility: https://web.dev/articles/content-visibility
- MDN content-visibility / contain / DocumentFragment / IntersectionObserver / Scheduler.yield
- Nolan Lawson — Improving rendering performance with CSS content-visibility: https://nolanlawson.com/2024-09-18/improving-rendering-performance-with-css-content-visibility/
- content-visibility measured (15x forced-layout reduction): https://dev.to/jangwook_kim_e31e7291ad98/content-visibility-measured-one-css-line-15x-less-forced-layout-3c03
- virtua (Solid adapter, feature matrix, keyboard nav): https://github.com/inokawa/virtua
- TanStack Virtual: https://tanstack.com/virtual/latest
- @solid-primitives/virtual: https://github.com/solidjs-community/solid-primitives/tree/main/packages/virtual
- Virtual scroll library comparison: https://pdanpdan.github.io/virtual-scroll/compare/
- scheduler.yield (Chromium 129+, MessageChannel fallback): https://developer.chrome.com/blog/use-scheduler-yield, https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield
- Solid 2.0 control flow (unified For): https://github.com/solidjs/solid/blob/next/documentation/solid-2.0/03-control-flow.md
- View Transitions: https://developer.chrome.com/docs/web-platform/view-transitions
- OPFS sync access handles in workers: https://renderlog.in/blog/origin-private-file-system-opfs/
- OPFS media cache example: https://github.com/KhoaTheBest/opfs-media-cache