实现说明
值得阅读的是函数 swapArticle,其余是驱动代码。
await 标出每个异步边界——没有 fire-and-forget。
使用要点
- 浏览器才是这里的运行环境:
document、fetch在 Node 里拿不到。 - 每一步打印都带着自己的标签:
swap complete for article。
常见问题
「startViewTransition 包裹 DOM 更新」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
签名一览:async function swapArticle(next: Article)
核心语句
const response = await fetch(`/api/articles/${next.id}`);
const body: Article = await response.json();
await transition.updateCallbackDone;
代码示例
// 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);