Feature detection of View Transition Types
- Published at
- Updated at
- Reading time
- 2min
I've been working on the new Web Weekly website and implemented the fairly new View Transition Types to trigger different view transitions depending on specific actions. I discovered that the usual feature detection doesn't work. Let's dive in!
View Transitions support is still fairly new across browsers.
| 111 | 111 | 111 | 144 | 144 | 18 | 18 | 22.0 | 111 |
Of course, it depends on your browser support, but I will go with implementing feature detection when using View Transitions. To do so, it's usually fine to check for document being available.
// "standard" view transition feature detection
if (document.startViewTransition) {
document.startViewTransition(() => {
// update the DOM
});
}
If you now want to use View Transition Types, the simple feature detection testing document won't work because startViewTransition can be used with a different syntax.
// only checking for `startViewTransition` won't work for
// browsers not supporting view transition types
if (document.startViewTransition) {
document.startViewTransition({
update() {
// update the DOM
},
types: ["theme-switch"],
});
}
Note that when you pass in the View Transition Types, startViewTransition isn't called with a callback function but with a configuration object containing an update function (the initial callback) and the desired types. Firefox, in my case now, does support startViewTransition but doesn't support the new View Transition object syntax.
It took me a while to figure it out, so here's how you can feature detect View Transition Types.
const supportsViewTransitions = !!document.startViewTransition;
// feature detection for View Transition Types
const supportsViewTransitionTypes = typeof ViewTransitionTypeSet !== "undefined";
if (supportsViewTransitions && supportsViewTransitionTypes) {
document.startViewTransition({
update() {
// update the DOM
},
types: ["theme-switch"],
});
}
And there we go! In this scenario, Firefox will not run any View Transitions because it doesn't support View Transition Types. All the other browsers are good to go then!
Join 6.2k readers and learn something new every week with Web Weekly.
