Multi-Page App View Transitions Are Here!
You can now transition fully static HTML pages
Jul 9, 2024
View Transitions for the same document, a single-page app, are currently supported in Chrome, Edge, and Safari but now Chrome 126 also adds support for cross-document View Transitions. This means you can now transition two static HTML pages hosted on the same domain.
This is a huge win for web apps as it makes implementing page transitions even simpler. Same-document View Transitions already made it much easier to implement page transitions in single-page apps but cross-document View Transitions take this to the next level.
It means you can get rid of your SPA altogether and build your app as a set of static HTML pages while keeping your fancy page transitions.
How it works
To enable cross-document View Transitions in your web app, pages need to opt-in to these transitions. In the first implementation, you had to add a <meta> tag to each HTML page but this has now been moved to CSS with the @view-transition at-rule:
@view-transition {
navigation: auto;
}
This is basically all you need to add to all the HTML pages you want to transition and you’ll get a nice fading transition by default. While this is great, fading transitions are, well, a bit boring so let’s customize it!
Let’s have a look at the sliding transition of What PWA Can Do Today that you can find in many native apps. It looks like this:
Here’s part of the CSS for it:
[data-transition="slide"]::view-transition-old(root) {
animation-name: slide-out;
}
[data-transition="slide"]::view-transition-new(root) {
animation-name: slide-in;
mix-blend-mode: normal;
}
The old page is represented by the ::view-transition-old(root) pseudo-element and the new page by the ::view-transition-new(root) pseudo-element. The app includes a View Transitions demo where you can select an animation for the pages which is selected by setting the animation name as a data-transition attribute on the <html> element. So for the "slide" animation, you would get:
<html data-transition="slide">
and the CSS uses the [data-transition="slide"] attribute selector.
Other CSS animation properties are set on both pseudo-elements, for example:
::view-transition-new(root),
::view-transition-old(root) {
animation-duration: 300ms;
animation-timing-function: cubic-bezier(0.465, 0.183, 0.153, 0.946);
animation-direction: normal;
}
This will add the sliding page transitions, but when navigating back the new page would need to slide back out to the right of the screen. With the CSS in the previous example, however, all new pages will slide in from the right including pages that you navigate back to which is clearly not what we want.
The back navigation needs to be different and we can apply a different animation by setting a class on the <html> element depending on if we're navigating forward or backward.
Here’s how you could do it:
// set "back-transition" class when navigating back
if(isBackNavigation()) {
document.documentElement.classList.add('back-transition');
}
// get the new page somehow
const template = getNewPageHTML();
const transition = document.startViewTransition(async () => {
document.body.innerHTML = template;
try {
// wait for the transition to finish
await transition.finished;
}
catch(e) {
console.error('error in transition:', e);
}
finally {
// remove "back-transition" class
document.documentElement.classList.remove('back-transition');
}
});
And now we can change the transition on back navigation like this:
[data-transition="slide"].back-transition::view-transition-new(root) {
animation-name: slide-out-reverse;
}
[data-transition="slide"].back-transition::view-transition-old(root) {
animation-name: slide-in-reverse;
mix-blend-mode: normal;
z-index: 1;
}
While this works, we always need to add a class to the <html> element (or another parent) and remove it after the transition has finished. If we forget to do that, we may break the transition.
Luckily, the new spec adds a better way.
View Transition Types
With View Transition Types, you can assign one or more types to an active view transition. So instead of adding a class to <html>, we assign a type to the transition based on if we're navigating forward or backward.
That way, we don’t have to modify the HTML and the type will be automatically removed when the transition has finished:
// determine the transition type
const direction = isBackNavigation() ? 'back' : 'forward';
// get the new page somehow
const template = getNewPageHTML();
document.startViewTransition({
update: () => {
document.body.innerHTML = template;
},
// set the transition type
types: [direction]
});
document.startViewTransition now receives an object whose update property holds the function that updates the view and whose types property holds an array of transition types. When navigating forward, the forward type will be applied and on back navigation, the back type will be applied.
In our CSS, we can now use the :active-view-transition-type pseudo-class to define rules depending on the active transition type:
/* forward navigation */
html:active-view-transition-type(forward) {
&[data-transition="slide"]::view-transition-old(root) {
animation-name: slide-out;
}
&[data-transition="slide"]::view-transition-new(root) {
animation-name: slide-in;
mix-blend-mode: normal;
}
}
/* back navigation */
html:active-view-transition-type(back) {
&[data-transition="slide"]::view-transition-new(root) {
animation-name: slide-out-reverse;
}
&[data-transition="slide"]::view-transition-old(root) {
animation-name: slide-in-reverse;
mix-blend-mode: normal;
z-index: 1;
}
}
The previous examples all applied to same-document View Transitions but you can also use transition types for cross-document View Transitions.
The pageswap and pagereveal events
To use transition types with cross-document View Transitions, the pageswap and pagereveal events were added to the spec.
The pageswap event is fired right before the snapshot of the old view is taken and pagereveal is fired right before the snapshot of the new view is taken. This enables you to make some last-minute changes on both pages.
For the page transitions of What PWA Can Do Today, I found I need to use pagereveal to set the correct transition type for a forward or back navigation:
window.addEventListener("pagereveal", async (e) => {
// if a view transition is running, the "viewTransition"
// property of the event will be "true"
if(e.viewTransition) {
// get the URL of the page we're navigating away
// from using the Navigation API
const fromURL = navigation.activation.from.url.replace(base, '');
// if we navigate away from the homepage it's a
// forward navigation,otherwise back
const navigationType = fromURL === '/' ? 'forward' : 'back';
// add the correct transition type
e.viewTransition.types.add(navigationType);
// scroll the home page to the top when navigating back
if(navigationType === 'backnavigation') {
window.scrollTo(0, 0);
}
}
});
We can then use the same CSS as in the previous example to customize the transitions for the old and new views but we also need to add the used transition types to the @view-transition at-rule:
@view-transition {
navigation: auto;
types: back, forward;
}
Making sure your pages load as fast as possible
With cross-document View Transitions we’re of course dealing with full page loads whenever we navigate from one page to another so we need to make sure all pages load fast otherwise the transitions won’t feel responsive.
This can be challenging when your pages don’t load fast enough. I found that a good way of dealing with this is to add a Service Worker to your web app and in particular to let it serve streaming responses.
By default, the browser’s HTML parser renders HTML in a streaming fashion, which means that the browser can render HTML while it downloads the page. It doesn’t have to wait for the whole page to download but it can already start rendering while it’s downloading.
You could of course cache all HTML pages of your app in IndexedDB and let the Service Worker serve them, but there’s an even better and faster way.
By adding a Service Worker to your web app that uses the body property of a Response, which is a ReadableStream, you can make full HTML pages load blazing fast.
Whenever a page is fetched, we can access that ReadableStream in the body property of Response and start rendering HTML while it downloads:
fetch('/some/url')
.then(response => response.body)
.then(body => {
const reader = body.getReader(); // we can now read the stream!
}
Single-page apps typically use an app shell, which is the single page that the content is injected into. It usually consists of a header, footer, and a content area in between where the content for each page is placed.
The problem is that any content that is added to the HTML page after it has loaded is bypassing the streaming HTML parser and is, therefore, slower to render. By splitting all the pages into header, footer, and content and letting the Service Worker stream those parts, we can render pages incredibly fast.
This means it can start rendering the header of the page while the content and footer are still downloading, giving a huge performance benefit.
Let’s have a look at the code, in particular the fetch event handler that is invoked whenever an outgoing request is intercepted by the Service Worker:
const fetchHandler = async e => {
const {request} = e;
const {url} = request;
// if the page is static, stream it
if(isStaticHTML(url)) {
e.respondWith(getStreamedHtmlResponse(url));
}
else {
e.respondWith(
caches.match(request)
.then(response => response ? response : fetch(request))
);
}
};
self.addEventListener('fetch', fetchHandler);
The isStaticHTML() function can be any logic to determine if the fetched url points to a static HTML page that needs to be streamed.
If this is the case, the Service Worker will respond with the resulting stream from getStreamedHtmlResponse() that looks like this:
const templateFolder = '/src/templates';
// header template
const header = `${templateFolder}/header.html`;
// footer template
const footer = `${templateFolder}/footer.html`;
const getStreamedHtmlResponse = (url) => {
const stream = new ReadableStream({
async start(controller) {
const pushToStream = stream => {
const reader = stream.getReader();
return reader.read().then(function process({value, done}) {
if(done) {
return;
}
controller.enqueue(value);
return reader.read().then(process);
});
};
const templates = [
caches.match(header),
// content, for example /src/templates/home.html
caches.match(`${templateFolder}${url}.html`),
caches.match(footer),
];
const responses = await Promise.all(templates);
for (const template of responses) {
await pushToStream(template.body);
}
controller.close();
}
});
// the stream is the body of the returned response
return new Response(stream, {
headers: {'Content-Type': 'text/html; charset=utf-8'}
});
};
Inside getStreamedHtmlResponse we construct a new ReadableStream that is passed an underlyingSource object, containing the start method which is called immediately after the stream is constructed.
start is passed a controller argument which is a ReadableStreamDefaultController that allows control of the internal state and queue of the ReadableStream.
Inside the start method, we fetch the templates for the HTML page and push the contents of the templates as individual streams into the main stream using the pushToStream function.
This function reads the individual streams from the templates chunk by chunk and enqueues them using controller.enqueue().
Since the start function is asynchronous, a new Response is immediately returned with the ReadableStream as the body of the response.
The browser can now stream the response and the page appears on the screen nearly instantly.
One more thing…
Although cross-document View Transitions work fine in Chrome 126 on Android, there is still an issue when a web app that uses cross-document View Transitions is installed as a PWA.
When installed and navigating to another page, the browser UI briefly shows up at the top of the screen which prevents the transition from being smooth as you can see in this screen recording:
There is already a bug report for this issue so hopefully this will be fixed soon.