Sub topic 9
Feature detection and graceful fallback
This chapter assumes you can write basic JavaScript with promises and async/await. It also assumes you have read the earlier chapters on document.startViewTransition(), the update callback, and the pseudo-element tree. Here you make that code safe to ship to every browser.
Why a fallback is required
A view transition is an enhancement. The page must work the same without it, because several things can stop the animation:
- The browser does not implement
document.startViewTransition(). - The user prefers reduced motion (covered in the next chapter).
- The browser skips the transition at runtime, for example when the document is hidden.
- Another transition starts and replaces the current one.
Calling document.startViewTransition() where it is undefined throws a TypeError. If your navigation code throws before it updates the DOM, the user sees a broken page, not just a missing animation. The rule is that the DOM update must run exactly once in every case, with or without animation.
Detecting support
Check for the method itself. Do not parse user-agent strings, because they go stale and misreport browsers.
function updateView(nextId) {
document.querySelector('#content').innerHTML = renderItem(nextId);
}
function navigate(nextId) {
if (!document.startViewTransition) {
updateView(nextId);
return;
}
document.startViewTransition(() => updateView(nextId));
}The guard returns early after calling updateView directly. Without the return, a supporting browser would run the update twice, and an unsupporting one would throw.
A check like typeof document.startViewTransition === 'function' is slightly stricter and equally valid. It also behaves well if some script has replaced the property with a non-function value.
Putting the check in one place
Scattering if (!document.startViewTransition) through an app invites mistakes. Wrap it once and call the wrapper everywhere.
const canTransition = typeof document.startViewTransition === 'function';
async function withTransition(update) {
if (!canTransition) {
await update();
return null;
}
const transition = document.startViewTransition(update);
// A skipped transition rejects `ready`. The update still runs,
// so there is nothing to recover. Silence the rejection.
transition.ready.catch(() => {});
await transition.updateCallbackDone;
return transition;
}
async function navigate(nextId) {
await withTransition(async () => {
const html = await loadItem(nextId);
document.querySelector('#content').innerHTML = html;
});
document.querySelector('#content h1')?.focus();
}Points to notice:
- The wrapper has the same shape on both paths. Callers can
awaitit and get "the DOM is updated" either way. updatemay beasync. In a supporting browser the browser waits for the returned promise before capturing the new state. In the fallback you mustawaitit yourself.- The wrapper returns the
ViewTransitionobject, ornull. Callers that needfinishedmust handlenull. - The code after
await withTransition(...)(here, moving focus) runs on both paths.
Rejected promises are not always errors
The ViewTransition object exposes three promises. Their behavior in failure cases matters for fallback code.
| Promise | Settles when | Rejects when |
|---|---|---|
| `updateCallbackDone` | The update callback finishes | The callback throws or returns a rejected promise |
| `ready` | The pseudo-elements exist and the animation is about to start | The transition is skipped or the callback fails |
| `finished` | The animation ends and the final state is shown | The callback fails |
When a transition is skipped, ready rejects with an AbortError, but the update callback still runs and the page still ends up in the new state. If you do not attach a handler to ready, the browser logs an "Uncaught (in promise)" error. That message is noise in the skip case. Handle it on purpose, as the wrapper does, and keep real errors visible by not swallowing updateCallbackDone or finished.
Keeping animation CSS out of unsupported browsers
Unsupporting browsers ignore ::view-transition-* rules, so they cause no harm there. You may still want to apply styles only when you actually start a transition. A class on the root element gives you that control, and it also lets you vary animations by interaction.
async function withTransition(update, { className = 'vt-active' } = {}) {
if (typeof document.startViewTransition !== 'function') {
await update();
return;
}
document.documentElement.classList.add(className);
const transition = document.startViewTransition(update);
transition.ready.catch(() => {});
try {
await transition.finished;
} finally {
document.documentElement.classList.remove(className);
}
}.vt-active::view-transition-old(root) {
animation: 250ms ease-out both fade-out;
}
.vt-active::view-transition-new(root) {
animation: 250ms ease-in both fade-in;
}
@keyframes fade-out { to { opacity: 0; } }
@keyframes fade-in { from { opacity: 0; } }The finally block removes the class even when the transition fails. Leaving it behind would apply the custom animations to later transitions you did not intend them for. Note that finished rejects if the update callback fails, so withTransition also rejects in that case, and the caller sees the real error.
Testing the fallback
Feature detection code that you never run on the fallback path tends to rot. You can force the fallback in any modern browser's DevTools console:
document.startViewTransition = undefined;After this line, typeof document.startViewTransition is 'undefined' and your guard takes the direct path. Reload the page to restore the native method. Check three things:
- Navigation still changes the content.
- Focus, scroll position, and the URL update the same as with transitions.
- The console shows no errors.
Also test the skip path. Start a transition and switch to another tab before it finishes, or trigger two navigations in quick succession. The final content must be correct both times.
Common mistakes
- Detecting with a CSS check only. CSS support queries cannot tell you whether the JavaScript method exists. Your script decides whether to call it, so detect in JavaScript.
- Running the update only inside the transition callback after a failed guard. The fallback must call the update itself.
- Duplicating the update logic. Write the update once as a function and pass it to both paths, as
updateViewdoes above. - Assuming the animation happened. Code that depends on animation timing, such as removing an element after 300 ms, breaks on the fallback path. Tie follow-up work to
finished, or avoid depending on animation at all. - Treating
readyrejection as a failure. It is the normal result of a skipped transition.
Exercise
A teammate writes const t = document.startViewTransition(update); t.ready.then(() => { history.pushState({}, '', url); });. Give two ways this code breaks, and show one fix.
Show answer
First, in a browser without startViewTransition, the call throws a TypeError, so neither the update nor the URL change happens. Second, when a transition is skipped, ready rejects, so pushState never runs and the URL does not match the view, and the rejection is also logged as unhandled. A fix is to move the URL change into the update callback, or to run it after await t.updateCallbackDone, and to wrap everything in a helper that checks typeof document.startViewTransition === 'function' and falls back to calling update() directly. Add t.ready.catch(() => {}) to silence the expected skip rejection.