3 min read

The Back/Forward Cache Was Already Working

  • Performance
  • Browsers
  • JavaScript
  • Testing

Press Back and one of two things happens. Either the previous page is rebuilt from scratch, or it comes back instantly from the back/forward cache, with its scroll position and its running JavaScript intact. I set out to get this site into that cache. It turned out to be there already, and the more useful result was learning why.

The premise

The home page keeps a WebSocket open to show how many people are here right now. The usual advice is that an open WebSocket keeps a page out of the back/forward cache, so the plan was to fix that.

What I measured

Before changing anything, I measured the live site in full Chromium. The stripped-down headless browser that test runners often use opts out of the cache entirely, so a test there can only ever answer no. With the real socket open, the home page, a post and the status page were all restored: pageshow reported persisted, the same JavaScript context came back, and Chrome reported no reason for blocking it.

The reason was already in the code. The presence script closes its socket when the tab is hidden and opens a new one when the tab is shown again. I checked that too: the first socket closed before the page was left, and a second one opened after the restore and received messages.

The old blockers aren't always blockers

Much of the advice about the cache is out of date. In the Chrome I tested, a page with an unload handler, a page sent with Cache-Control: no-store, and a page with a request still in flight could all be restored. Those used to be the classic reasons a page was left out.

A guard instead of a fix

With nothing to fix, the work became making sure it stays that way:

  • A check I run by hand. pnpm check:bfcache leaves each page and comes back. When a page is not restored, it fails with Chrome's own reason. To see it fail, I opened a popup from the page, which Chrome reports as RelatedActiveContentsExist.
  • A unit test that runs on every change. It fails the build if someone adds an unload or beforeunload handler, removes the socket's close on hide, or sends no-store.

What I'd tell someone else

  • Measure before you fix. The plan was built on advice that was true once. Measuring in a real browser first saved a fix for a problem that did not exist.
  • Test the real thing. Playwright's mocked WebSocket is a script shim, not a real socket, so my local end-to-end tests said nothing about how the real one behaves.
  • Automated browsers often switch the cache off. When I later added a daily check from a headless browser, its Chromium reported BackForwardCacheDisabledByCommandLine. That check now records "can't tell" instead of a false "not restored".
  • Say what you didn't test. I only measured Chromium. Safari and Firefox have their own rules.