# 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`/`search3` are 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. ```css .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 `) or the scrollbar jumps / CLS explodes. The `auto` keyword 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-visibility` on 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 ```css .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 `transform` and `opacity` (compositor-only, no layout/paint). Position virtualized items with `transform: translateY()` (virtua/tanstack both do this) — never `top`. - `will-change: transform` **only** on elements that are actually animating right now, and remove it after — blanket `will-change` wastes GPU memory and can make things slower. - Avoid `box-shadow`, `filter`, `backdrop-filter` on scrollable row content; pre-render effects into images or apply them only to hover/focus states of a single row. - `contain: paint` gives you a compositing boundary for free. ### DOM-write discipline - **Batch writes, then read.** Interleaved `element.offsetHeight` reads after writes cause layout thrash. In scroll handlers: read `scrollTop` once (passive listener), compute, then write. - Build subtrees in a **`DocumentFragment`** and 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 call `preventDefault` in them). - `overscroll-behavior: contain` on inner scroll panes stops scroll chaining and avoids full-page rubber-band work — great for the multi-pane layout we want. - `overflow-anchor: none` on 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: ```ts function yieldToMain(): Promise { 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(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: `` inside a fixed `aspect-ratio: 1` container (so layout never shifts when the image lands). `decoding="async"` keeps decode off the main-thread paint path. - `` for art beats CSS `background-image` for 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 (via `idb`) for metadata, favorites, config only. - Feed `