startViewTransition Wraps DOM Updates
startViewTransition snapshots the old DOM, awaits the update callback, then animates between snapshots; ViewTransition exposes the phases as three promises.
Code
// startViewTransition snapshots the old DOM, runs the update, then animates
// between the two snapshots. The ViewTransition object models the phases
// with three promises.
interface Article {
id: string;
title: string;
}
async function swapArticle(next: Article): Promise<void> {
const transition = document.startViewTransition(async () => {
// The update may be async: the browser waits for this promise before
// capturing the new snapshot and starting the animation.
const heading = document.querySelector<HTMLHeadingElement>('#article-title');
if (heading) heading.textContent = next.title;
const response = await fetch(`/api/articles/${next.id}`);
const body: Article = await response.json();
const views = document.querySelectorAll<HTMLElement>('.article-view');
views.forEach((view) => {
view.dataset.articleId = body.id;
});
});
// updateCallbackDone resolves when the DOM update itself succeeded
await transition.updateCallbackDone;
// ready resolves when both snapshots exist and the animation starts
await transition.ready;
// finished resolves when the crossfade is done
await transition.finished;
console.log('swap complete for article', next.id);
}
const nextArticle: Article = { id: '42', title: 'View transitions in practice' };
void swapArticle(nextArticle);What the code does
startViewTransition Wraps DOM Updates comes down to the function swapArticle.
Every asynchronous step is awaited, so rejections surface where the call happens.
Watch out for
- The snippet leans on
document,fetch— browser-only surfaces a bare Node process cannot provide.
Using it
The entry-point signature is async function swapArticle(next: Article)
Output lines are prefixed (swap complete for article), making each step’s effect easy to spot.
Key statements
const response = await fetch(`/api/articles/${next.id}`);
const body: Article = await response.json();
await transition.updateCallbackDone;
Interactive Tools for This Topic
FAQ
- Does startViewTransition Wraps DOM Updates run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.