10LOC

#performance

Web Platformintermediate

Use requestVideoFrameCallback for smooth animation timing

type RvfcVideo = HTMLVideoElement & {
  requestVideoFrameCallback: (cb: (now: number, meta: { mediaTime: number }) => void) => number;
  cancelVideoFrameCallback: (handle: number) => void;
};

Schedule visual work with the browser's video frame callback for smoother rendering.

Chrome APIsadvanced

The Speculation Rules API to prerender the next likely page

const injectedUrls = new Set<string>();

export const prerenderOnHoverIntent = (link: HTMLAnchorElement, dwellMs = 200) => {
  if (!(globalThis as any).HTMLScriptElement?.supports?.("speculationrules")) return;
  let timer = 0;

A dynamically-injected <script type=speculationrules> can prerender a hovered link in the background, so the click lands on an already-rendered page.

Web Platformadvanced

Transferable objects with postMessage for zero-copy worker handoff

const { port1, port2 } = new MessageChannel();

port2.onmessage = (event: MessageEvent<ArrayBuffer>) => {
  console.log("received", event.data.byteLength, "bytes, zero-copy");
};

Passing an ArrayBuffer in postMessage's transfer list hands off ownership instead of cloning it — the sender's reference goes to byteLength 0.

Chrome APIsintermediate

content-visibility: auto to skip render cost offscreen

.long-page section {
  content-visibility: auto;
  contain-intrinsic-size: auto 480px;
}

content-visibility: auto skips layout, style, and paint for an off-screen subtree — near-free virtualization that keeps find-in-page and anchors working.

Web Platformintermediate

Page Visibility API to pause work in a backgrounded tab

export const pauseWhenHidden = (start: () => () => void) => {
  let stop = start();

  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "hidden") {

Stop polling, ticking, or rendering the instant a tab goes to the background, and resume with the same start function when it comes back.

Chrome APIsadvanced

WebCodecs for low-level video frame processing

// @types/dom-webcodecs isn't installed in this repo, so VideoDecoder/VideoFrame/
// EncodedVideoChunk aren't typed here — cast to `any` rather than pretend otherwise.
export const decodeFrames = (chunks: any[], onFrame: (frame: any) => void): Promise<void> => {
  const Decoder = (globalThis as any).VideoDecoder;
  const decoder = new Decoder({

VideoDecoder exposes the browser's own hardware decoder as a queue: feed chunks in, get real VideoFrame objects out — no ffmpeg.wasm, no <video> polling.

Web Platformadvanced

The Cache API for direct HTTP response caching

const CACHE_NAME = "api-cache-v1";

export const fetchWithCache = async (url: string, maxAgeMs: number) => {
  const cache = await caches.open(CACHE_NAME);
  const cached = await cache.match(url);

Cache real Response objects by URL from plain page scripts, with a manual max-age check, no service worker required.

Bunintermediate

Benchmarking Bun's cold start against Node with performance.now()

const measureColdStart = (cmd: string[]) => {
  const start = performance.now();
  Bun.spawnSync(cmd);
  return performance.now() - start;
};

Bun.spawnSync plus performance.now() around each call turns a cold-start comparison against Node into a five-line, dependency-free benchmark.

Web Platformintermediate

requestIdleCallback for scheduling non-urgent work

type IdleCallback = (deadline: IdleDeadline) => void;

const runOnNextTick = (callback: IdleCallback) => {
  const start = performance.now();
  setTimeout(() => callback({ didTimeout: false, timeRemaining: () => Math.max(0, 50 - (performance.now() - start)) }), 1);

Run analytics, prefetching, or cache warming only when the browser has real spare time, with a fallback for the one major browser that never shipped this API.

Bunadvanced

Calling a C function from Bun via bun:ffi

import { dlopen, FFIType, suffix } from "bun:ffi";

const path = `libsqlite3.${suffix}`;

const { symbols } = dlopen(path, {

bun:ffi's dlopen loads a shared library and JIT-compiles a JS-to-native binding for each symbol, letting Bun call C functions directly with no N-API glue code.

Node.jsintermediate

performance.now() / hrtime.bigint() for accurate micro-benchmarks

import { performance } from "node:perf_hooks";

const benchmark = (fn: () => void, iterations = 100_000) => {
  const start = process.hrtime.bigint();
  for (let i = 0; i < iterations; i++) fn();

process.hrtime.bigint() gives nanosecond integer precision for micro-benchmarks; performance.now() is ms-resolution and good enough for most cases.

Chrome APIsadvanced

scheduler.postTask to yield to the main thread under load

type TaskPriority = "user-blocking" | "user-visible" | "background";
type PostTask = (cb: () => void, opts?: { priority?: TaskPriority }) => Promise<void>;

const postTask = (globalThis as { scheduler?: { postTask: PostTask } }).scheduler?.postTask;

scheduler.postTask breaks a long loop into prioritized chunks with real cancellation — a purpose-built replacement for setTimeout(fn, 0).

Web Platformintermediate

ResizeObserver for a responsive component with no resize listener

const setLayout = (el: HTMLElement, width: number) => {
  el.classList.toggle("is-wide", width >= 560);
  el.classList.toggle("is-compact", width < 320);
};

Give a component its own width-based breakpoints, driven by its actual box size instead of the window's, with no global resize listener at all.

Node.jsadvanced

worker_threads for CPU-bound work off the main thread

import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

const fibonacci = (n: number): number => (n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2));

if (isMainThread) {

Offload a genuinely CPU-heavy computation to a worker_threads Worker so it stops blocking the event loop, using one self-contained file.

Reactintermediate

useTransition to keep input responsive during expensive updates

import { useState, useTransition } from "react";

export const FilterableList = ({ items }: { items: string[] }) => {
  const [text, setText] = useState("");
  const [visible, setVisible] = useState(items);

Mark an expensive state update as a transition so React keeps typing responsive and only shows the update once it is ready.

Web Platformintermediate

IntersectionObserver for lazy-loaded images in 10 lines

const observer = new IntersectionObserver((entries, obs) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    const img = entry.target as HTMLImageElement;
    img.src = img.dataset.src ?? "";

Load images only when they're about to enter the viewport, using one shared observer instead of a scroll listener per image.

Reactintermediate

useDeferredValue for a jank-free typeahead search

import { useState, useDeferredValue, useMemo } from "react";

const filterItems = (items: string[], query: string) =>
  items.filter((item) => item.toLowerCase().includes(query.toLowerCase()));

Defer expensive list re-renders behind fast keystrokes with useDeferredValue, and show a stale-content hint while it catches up.