BFCache 与 View Transitions 协同优化返回导航体验概述返回导航(后退/前进)在现代浏览器中常通过 BFCache(Back/Forward Cache)瞬时恢复页面状态。本文给出与 View Transitions API 的协同策略:既保留即时恢复优势,又保证过渡体验与可访问性一致。关键参数/概念BFCache 事件:`pageshow`/`pagehide` 的 `event.persisted` 标识是否由 BFCache 恢复。过渡入口:`document.startViewTransition(callback)` 用于同文档过渡;跨文档过渡依赖两端元素的 `view-transition-name` 匹配。可访问性偏好:通过 `prefers-reduced-motion` 降低动画强度或禁用动画。实践/示例1) BFCache 恢复检测与过渡禁用// 恢复自 BFCache 时跳过进入动画,避免重复过渡与闪烁
window.addEventListener('pageshow', (e) => {
const restoredFromBFCache = e.persisted === true;
document.documentElement.toggleAttribute('data-bfcache', restoredFromBFCache);
});
// 示例:进入页面时的淡入过渡,仅在非 BFCache 恢复时启用
function enterTransition(run) {
const prefersReduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const fromBFCache = document.documentElement.hasAttribute('data-bfcache');
if (prefersReduce || fromBFCache || !document.startViewTransition) {
run();
return;
}
document.startViewTransition(() => run());
}
// 页面初始化:
enterTransition(() => {
// 初始化逻辑,例如渲染首屏数据
});
2) 跨文档共享元素过渡与返回一致性<!-- 两端页面为共享元素声明一致名称 -->
<style>
.avatar { view-transition-name: user-avatar; }
::view-transition-old(user-avatar),
::view-transition-new(user-avatar) {
animation: fade 180ms ease;
}
@keyframes fade { from { opacity: 0 } to { opacity: 1 } }
@media (prefers-reduced-motion: reduce) {
::view-transition-old(user-avatar),
::view-transition-new(user-avatar) { animation: none }
}
</style>
3) 焦点管理与输入恢复// BFCache 恢复后保留输入状态,但需确保焦点可见与键盘导航可达
window.addEventListener('pageshow', (e) => {
if (e.persisted) {
const active = document.activeElement;
if (active && typeof active.scrollIntoView === 'function') {
active.scrollIntoView({ block: 'nearest' });
}
}
});
验证方法事件验证:在 `pageshow/pagehide` 监听 `event.persisted`,确认 BFCache 命中与恢复路径。性能对比:采集返回导航后的 `INP/LCP`,与禁用 BFCache/过渡的对照组比较。视觉一致性:跨文档共享元素在前进/后退路径下均应保持匹配与过渡自然。注意事项避免在 `unload` 上做清理,使用 `pagehide`,以兼容 BFCache。过渡过程减少强制同步布局与重排,保持动画主线程轻量。对 `prefers-reduced-motion` 提供降级;确保键盘与读屏流畅。参考资料MDN: Window `pageshow`/`pagehide` 事件与 BFCache(2025 更新)https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_eventhttps://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_eventMDN: ViewTransition 与 `startViewTransition()`(2025-11 更新)https://developer.mozilla.org/en-US/docs/Web/API/ViewTransitionhttps://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition

发表评论 取消回复