← Case study

Detail 14 · Performance

Fast, light and accessible

Keeping all this motion smooth: what a frame is and how they were counted, what moves cheaply, layers while things move, and the bytes. 10 minutes, 2 demos.

Try it: what a frame is

5 frames a second, one every 200 ms

01 · The idea

Motion shouldn't be the price of entry

Everything on this site moves: pages sink and get sketched, letters swell, strings ring, grain jumps. None of it is worth anything if the page stutters, takes long to arrive, or can’t be used by someone who can’t use a mouse or gets dizzy from motion. So three rules sat under all of it: smooth on an ordinary laptop, light on a phone, and usable by anyone.

This detail is the plain side of the site: what a smooth frame is and how I counted them, the habits that keep it fast, what the numbers changed and what they didn’t, and where the bytes go. The switch that calms it all down has a detail of its own.

02 · A frame

Sixty pictures a second

Nothing on a screen really moves. The browser draws a picture, then another a little later, and your eye joins them up. Each picture is a frame, and a screen asks for sixty a second: one every 16.7 milliseconds. Draw them all in time and a dot glides; miss some and it hops.

Below, a dot crosses the stage in a second, drawn only on the frames it gets. At five a second there are five places it’s seen and nothing in between. Raise the rate and new frames land between the ones already there, until the copies run together into a line and the hop becomes a glide.

What a frame is

5 frames a second, one every 200 ms

A frame that isn’t ready in time isn’t skipped: the old one stays up. So a stutter is a frame held for two, 33 milliseconds instead of 16.7, and the dot standing still while time goes on. Switch “Drop a frame” on to see one: a gap in the strip, and the dot waiting where it was.

03 · Counting

How the frames were counted

The browser will tell you when it draws. Ask requestAnimationFrame for a callback and it calls once, just before the next frame; ask again from inside it and you get one call per frame. The time between two calls is how long that frame took. Record every gap while something plays, and three numbers come out of it:

A frame recorder, pasted into the console
const gaps = [];
let last = performance.now();
let recording = true;

function tick(now) {
  gaps.push(now - last);
  last = now;
  if (recording) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);

// Play the animation, then stop and count
recording = false;
const fps = gaps.length / (gaps.reduce((sum, gap) => sum + gap, 0) / 1000);
const stutters = gaps.filter((gap) => gap > 33).length; // a frame held for two or more
const worst = Math.max(...gaps); // the one hitch you'd notice

Frames a second says how smooth it was on average, the stutters how often it broke, and the worst gap how badly. An average hides a lot: 50 frames a second can be smooth all the way, or perfect with one long freeze.

The numbers are only worth something if the run is fair, so the ones in this detail were taken the same way (one exception, the book below, says so):

  • A production build. The development server checks everything twice and runs slower.
  • The same steps every time, after the page has settled for a couple of seconds, so a measurement of a scroll isn’t a measurement of the page still loading.
  • One thing changed at a time. To test a fix, I switched just that part off with a line of CSS injected into the page, then on again, back and forth, rather than comparing two builds an hour apart.
  • A visible tab. A tab in the background draws nothing, and the recorder sees nothing.
  • A control run. The same clicks and keys on empty space, to make sure it isn’t the measuring that’s slow.

When a number was bad, the browser’s long-animation-frame timing said why: how much of a slow frame was spent running script, and how much was layout and drawing. That’s what turned “the islands are slow” into “the islands take long to draw”, which is a different fix.

The recorder has one blind spot: it counts the frames the page’s own thread gets to. Animations the browser runs on its own, off that thread, can stay smooth while the recorder stutters. That’s exactly why they’re worth having, as the next part shows.

04 · Smooth

Only the cheap things move

A browser can move, scale and fade something almost for free, on the graphics card, without laying the page out again. Almost every animation here sticks to those: transforms and opacity. Anything that follows the pointer or the scroll runs on motion values, which change the style directly instead of re-rendering React, as the proximity detail showed.

How a transform is written matters too. Motion can hand an animation to the browser to run on its own, away from the page’s busy thread, but only when it’s given a whole transform. Split into x, y, rotate and scale, it has to work out each frame itself, in script. The pages of the home page’s pile used to spread that way. Now each place is one string:

One transform, run by the browser
// One transform string, not x / y / rotate / scale: Motion runs a whole transform on the
// browser's own engine, off the main thread the scroll needs
const transform = (x, y, rotate, scale) => `translate(${x}px, ${y}px) rotate(${rotate}deg) scale(${scale})`;

The spread went from about 45 frames a second to about 49, with a third fewer stutters. Not a big number, but it’s free: the pages land exactly where they did.

Blur is the exception to “cheap”, because it’s expensive while it’s on. The reveals blur things in, so once a block is sharp the filter is taken off altogether, not left at zero. Left on, every scroll would keep redrawing it.

Sharp, then no filter at all
animate={
  ready
    ? {
        opacity: 1,
        filter: "blur(0px)",
        scale: 1,
        // Drop the filter once sharp so scrolling doesn't keep re-rendering it
        transitionEnd: { filter: "none" },
      }
    : undefined
}

And things that are idle should cost nothing. The grain is drawn once and only moved, the demos pause their loops when they scroll out of view, and the music’s loops go to sleep while it’s paused.

05 · Layers

A layer while it moves

The browser can keep part of the page as a picture of its own, a layer, and move that picture around without drawing what’s on it again. Ask for one with will-change: transform. On this site that was the single biggest fix, three times over:

  • The pile on the home page drifts as you scroll, each page at its own speed. With no layers, every scroll frame redrew every page, its grain, drawings and shadows: about 27 frames a second. With a layer each, 60.
  • The hero has four layers moving at different speeds. Given layers of their own, scrolling past it went from about 33 frames a second to 60.
  • The page leaving at a change, sinking and fading, was redrawn whole on every frame: about 17 frames a second. With a layer while it sinks, about 35, on a day the browser held everything to half speed (on a normal day, 20 against 56).
A layer only while it sinks
const leaving = stage === "leaving";
return (
  <motion.main
    className={className}
    initial={false}
    animate={STAGE[stage]}
    transition={leaving ? LEAVE_TRANSITION : { duration: 0 }}
    // A layer while it sinks: without one the whole page is repainted every frame (~20fps)
    style={{ transformOrigin: leaveOrigin, willChange: leaving ? "transform, opacity, filter" : undefined }}

So why not a layer on everything? Because a layer is a picture, taken at one size. The pile’s pages grow a tenth as they spread out, and a page that kept its layer kept the smaller picture, stretched: its text went soft. So a page gets its layer only while it travels and drops it once it lands, to be drawn again, sharp, at its real size. And each layer costs memory on the graphics card: the book once kept thirty-five of them, more than a phone had, and the page glitched.

06 · Measured

What the numbers changed, and what they didn’t

The hero’s giant name used to write itself in with a pen, like the intro’s signature. Measured, it ran at about 15 frames a second on its own: three page-sized drawings redrawn through a mask on every frame. Started alongside the page’s reveal, both stuttered. It blurs in now, after the reveal, and its outline and its red copy start a moment apart: together they measured about 45 frames a second, apart about 57.

The book on the case study’s page felt sluggish to turn. The recorder agreed, six or seven frames a second, but the long-animation-frame timing said the page’s own thread was nearly idle: the time was going into drawing pixels. Switching things off one at a time found it in the paper. Its grain was an SVG with two noise filters, set as each page’s background, and an SVG background runs its filters again every time what it lies on is repainted. A turning page is repainted every frame, and so is a page whose corner follows the mouse.

So each grain is now drawn once, into a bitmap, after the page has loaded, and the pages use that. Until it’s ready, and in a browser that can’t take it, the SVG stays.

The grain, drawn once
export function rasterizeGrains() {
  if (started) return;
  started = true;
  // An unsupported value in the variable wouldn't fall back to the SVG: it would leave no grain
  if (!CSS.supports("background-image", 'image-set(url("x.png") 2x)')) return;
  // At least 2× the CSS size, so it stays sharp on scaled screens; image-set keeps its size
  const scale = Math.min(Math.max(Math.ceil(window.devicePixelRatio || 1), 2), 3);
  Object.entries(GRAINS).forEach(async ([name, { size, svg }]) => {
    try {
      const image = new Image();
      image.src = svg.slice(5, -2);
      await image.decode();
      const canvas = document.createElement("canvas");
      canvas.width = canvas.height = size * scale;
      canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
      const blob = await new Promise((resolve) => canvas.toBlob(resolve));
      if (!blob) return;
      document.documentElement.style.setProperty(`--${name}-grain`, `image-set(url("${URL.createObjectURL(blob)}") ${scale}x)`);

Turning went from about 7 frames a second to about 25, and the mouse over a page from 9 to 60, with the grain looking just as it did. The same hunt found every turn re-rendering all nineteen sheets of the book when three had changed; now a sheet re-renders only when the page it shows does.

Just as often, the numbers said to leave something alone:

  • The strings under the navbar ring with the music through a pencil filter, redrawn every frame. It looked expensive. Playing: 57.7 frames a second; with the filter off, 58.7. Not worth a change.
  • The islands take a long time to draw as they open, about 41 frames a second. Two textbook fixes measured no faster, and one let the page show through: the full story is in the islands’ detail.
  • The résumé’s flight on a phone reflows its text on every frame, a risk on paper. Measured, it costs about a millisecond a frame, not what sets the pace.

07 · Accessible

Anything you can hover, you can reach

A site this visual is easy to make for a mouse only. The rule here is that anything that reacts to hovering can also be reached from the keyboard and by touch. The scroll ruler’s index has a hidden “Jump to a section” stop for the keyboard and opens with a tap on a touchscreen. Demos that react to a cursor have a play button that runs one across them, for anyone without one.

Custom controls are real controls underneath. The pencil sliders are drawn over real range inputs, so arrow keys, screen readers and touch all work; the switches are buttons with the switch role. And the purely decorative layers, the grain, the strings and the sketches, are hidden from screen readers, so they don’t read out as noise.

08 · The numbers

Where the bytes go

Here’s what a first visit to the home page downloads, from a production build. Three fixes are in: the grain went from a 3.1 MB image to 600 bytes, the portrait is sized and converted by Next’s image component instead of sent as a 572 KB PNG, and the glow behind the hero is gone. Switch “Before the fixes” on to see what they saved.

Where the home page’s bytes go
  • JavaScript12 files281 KB
  • Fonts5 WOFF2 + the signature’s TTF268 KB
  • HTML185 KB before gzip22 KB
  • CSS2 files19 KB
  • The portraitWebP, sized by next/image10 KB
  • The grainan SVG inside the CSS0.6 KB
  • The glow behind the herogone: was a 1 MB PNG, sent as WebP0 KB

First visit, before the music601 KB

The biggest thing on the page was a blur. The soft orange glow behind the hero was a 1 MB PNG, and even converted to WebP it was 352 KB: more than all the JavaScript. It cost frames too, as a page-sized image drifting with every scroll. A CSS gradient could have kept it for nothing, but the hero read just as well without it, so it went. Now the JavaScript is the largest part, which is where it should be.

The fonts held a surprise too. The site asks for six weights of Roboto, which looks wasteful, but Roboto is a variable font: all six come from one file per style, so trimming them would save nothing. What’s worth checking instead is whether the italic Roboto, preloaded on every page, is used at all.

The music isn’t in the total. Each track is 3 to 8 MB, but it’s streamed after the page has loaded, and it never holds anything up.

09 · Decisions

Why it’s built this way

Transforms and opacity

The two things a browser moves for free. Everything else that animates has to earn it.

Hover is a bonus

Nothing important lives only behind a hover. The keyboard and a tap reach it too.

A layer while it moves

Drawn once and moved, then dropped when it lands, so it’s drawn again sharp. Kept for good, a layer goes soft and eats memory.

Measure, then fix

The obvious suspects, six weights of one font and a filter on the strings, cost nothing. The real costs were a blur, a page with no layer, and a noise filter run again every frame.

10 · Takeaways

What to keep

  • Animate transforms and opacity, as one transform; take filters off once they’ve done their job, and let idle things cost nothing.
  • Give what moves a layer while it moves, and only then.
  • Count frames, not feelings: a production build, one change at a time, compared in one sitting. A fix that doesn’t measure faster goes back out.
Watch the pile→

Scroll to “My crafts” on the home page: every page drifts past on a layer of its own.