Sub topic 11
The ViewTransition object: ready, finished, updateCallbackDone
This chapter assumes you can call document.startViewTransition() and know the capture, update, animate lifecycle from earlier chapters. You should also be comfortable with promises and async/await. Here you will learn what the returned ViewTransition object gives you. It has three promises that report where the transition is in its lifecycle, and each one settles at a different moment.
What startViewTransition() returns
document.startViewTransition() returns a ViewTransition object immediately. The browser has not captured anything yet when you get it. The object exposes:
updateCallbackDone: a promise for the DOM update.ready: a promise for the moment the animation is about to start.finished: a promise for the moment the transition is over.skipTransition(): a method that abandons the animation. Later chapters cover it.
The callback you pass does not run synchronously. The browser calls it later, after it has captured the old state. Code placed right after the startViewTransition() call therefore runs before your update callback does.
The three promises in order
The following script logs each stage. The fetchItemHtml function is a stub that stands in for a network request.
function fetchItemHtml(id) {
return new Promise((resolve) => {
setTimeout(() => resolve(`<h2 tabindex="-1">Item ${id}</h2>`), 200);
});
}
const transition = document.startViewTransition(async () => {
console.log('callback start');
const html = await fetchItemHtml(7);
document.querySelector('#content').innerHTML = html;
console.log('callback end');
});
console.log('after startViewTransition call');
transition.updateCallbackDone.then(() => console.log('updateCallbackDone'));
transition.ready.then(
() => console.log('ready'),
() => console.log('ready rejected')
);
transition.finished.then(
() => console.log('finished'),
() => console.log('finished rejected')
);In a supporting browser, the log reads as follows:
after startViewTransition callcallback startcallback endupdateCallbackDonereadyfinished, after the animation duration has passed.
What each promise means
| Promise | Fulfills when | Rejects when | Typical use |
|---|---|---|---|
| `updateCallbackDone` | The promise returned by your callback fulfills (or the callback returns normally). | The callback throws or its promise rejects. | Work that depends on the new DOM, whether or not the animation runs. |
| `ready` | The pseudo-element tree exists and the animation is about to start. | The transition is skipped before animating, the callback fails, or capture fails (for example, duplicate names). | Starting JavaScript animations on the pseudo-elements. |
| `finished` | The animation is done, the pseudo-elements are removed, and the live page is visible. | The callback throws or its promise rejects. | Cleanup of temporary names, classes, and state. |
Two details cause most of the confusion:
updateCallbackDoneis independent of the animation. It fulfills even when the browser skips the visual transition, for example in a hidden tab. This makes it the right promise to wait on for "the DOM is updated".readycan reject whilefinishedstill fulfills. If the transition is skipped, the update callback still runs and the page still ends up in the new state. Only the animation is lost.
Using updateCallbackDone for post-update work
Focus management, scroll restoration, and analytics events belong after the DOM update. They should not wait for the animation to finish, because keyboard and screen reader users need focus moved promptly.
async function openItem(id) {
const transition = document.startViewTransition(async () => {
const html = await fetchItemHtml(id);
document.querySelector('#content').innerHTML = html;
});
try {
await transition.updateCallbackDone;
document.querySelector('#content h2')?.focus();
} catch (error) {
console.error('Update failed:', error);
}
}If the callback fails, updateCallbackDone rejects and the catch block runs. In that case the browser abandons the animation and shows the live page.
Using finished for cleanup
Anything you set up for the transition, such as a temporary view-transition-name or a class on <html>, should be removed when the transition ends. finished fulfills at that point. Use finally so the cleanup also runs when the transition fails.
function navigateWithClass(update, className) {
const root = document.documentElement;
root.classList.add(className);
const transition = document.startViewTransition(update);
transition.finished.finally(() => root.classList.remove(className));
return transition;
}The shared-element example earlier in this tutorial used the same pattern. It cleared the temporary hero name from the detail image inside finished.finally(...).
Using ready for animation setup
ready is the only moment when the pseudo-elements exist but the default animations have not yet visibly progressed. It is the hook for the Web Animations API. The next chapter covers that API in detail, so here is only the shape:
const transition = document.startViewTransition(() => updateView());
try {
await transition.ready;
console.log('Pseudo-elements are available now.');
} catch (error) {
console.warn('Transition did not animate:', error);
}Wrap await transition.ready in try/catch. If you leave a rejection unhandled in your own code, the error can surface in a place that is hard to trace.
A wrapper that works everywhere
Browsers without the API return no ViewTransition, so code that reads transition.finished breaks there. A small wrapper keeps the calling code the same in both cases by returning a promise for the DOM update.
async function withTransition(update) {
if (!document.startViewTransition) {
await update();
return;
}
await document.startViewTransition(update).updateCallbackDone;
}
await withTransition(() => {
document.querySelector('#content').innerHTML = '<h2>Updated</h2>';
});This wrapper deliberately exposes only the update, because that is the part every browser can honor. If you need ready or finished, check for the API first and treat those stages as optional.
Common errors
- Reading the DOM right after
startViewTransition(). The callback has not run yet. Wait forupdateCallbackDone. - Starting animations without waiting for
ready. The pseudo-elements do not exist before then, so the animation targets nothing. - Cleaning up in
ready. The animation is only starting at that point. Removing a temporary name there changes what is animated. Clean up infinished. - Ignoring rejections. A thrown error in the callback rejects both
updateCallbackDoneandfinished. Handle at least one of them so failures are visible. - Making the callback slow. The page stays frozen on the old snapshot until your callback's promise settles. Do slow fetching before calling
startViewTransition()when you can.
Exercise
A user clicks a link, and your update callback runs but the browser skips the animation because the tab is hidden. Which of updateCallbackDone, ready, and finished fulfill, and which reject? Where should you put code that moves keyboard focus to the new heading?
Show answer
updateCallbackDone fulfills because the callback ran and its promise fulfilled. ready rejects because the animation never started. finished fulfills once the update is complete and the new state is shown. Focus code belongs after await transition.updateCallbackDone, because that runs whether or not the animation happened.
Exercise
You add a temporary class to <html> before starting a transition and want it removed even if the update callback throws. Which promise should you attach the removal to, and which method makes sure it runs on both success and failure?
Show answer
Attach it to transition.finished and use .finally(...). finished fulfills when the transition ends and rejects if the callback fails, and finally runs in both cases.