Paint holding with CSS


Some browsers have a nice feature called paint holding. When you navigate to another page on the same domain the browser will hold the previous page until the new content is loaded. This stops a white flash on navigation making multi page apps feel like single page apps.

Note: all my writing and code is handcrafted by me.

The problem with thin shims and streaming content

I'm a fan of streaming HTML which means I normally load a thin shim (that can be cached) and then stream in the HTML content over server sent events (SSE) using Datastar.

There's lots of benefits to this approach: better for compression, consistent views, bot blocking/protection, render batching etc (I won't be covering these in this post).

However, it does present a problem. It messes with paint holding. As navigation becomes:

Page A - content streamed in
shim (loaded from cache)
Page B - content streamed in

Paint holding only lasts until the shim is loaded, not until the content has streamed in. This results in a flash/pop because the shim is empty.

CSS to the rescue

However, we can do our own paint holding with view transitions:

@view-transition {
  navigation: auto;
}

::view-transition-old(root) {
  animation: hold-old-page 100ms both;
  mix-blend-mode: both;
}

::view-transition-new(root) {
  animation: none;
  opacity: 0;
}

@keyframes hold-old-page {
  from,
  to {
    opacity: 1;
  }
}

The above CSS sets the view transition to hold the old root for 100ms and then switch to the new root. Note this doesn't delay the loading/fetching of the new root.

You can try this out

Scroll somewhere and then tap the TOP CORNER link and you'll see it work. If you open your network tab you'll even see the navigation.

Conclusion

Hopefully, this post shows you some of the great stuff you can do with view transitions in modern browsers.

Code can be found here.

Thanks to Everyone on the Datastar discord who read drafts of this and gave me feedback.