单页应用的导航不仅是替换页面内容,还要维护浏览器历史、处理返回按钮、恢复滚动和避免旧请求覆盖新页面。本文使用原生 History API 组织一个小型文档管理界面,说明路由器背后的基本机制。示例使用固定路由表描述业务契约,生产环境应将路径定义集中维护。
1. 设计语义化导航
普通导航应保留真实的锚点和可访问名称。JavaScript 只增强站内可处理的导航,不应阻止打开新标签页等浏览器原生操作。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/7cd950c7ae4dbe0fcf4eed58d3136e3d39070abb">
<nav aria-label="主导航">
<a href="/workspace">工作台</a>
<a href="/workspace/settings">设置</a>
</nav>
</div>
2. 建立路由匹配入口
将路径匹配与渲染逻辑分开。对于未知路径返回明确的未找到视图,避免根据任意输入动态执行模块。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4f9a787a218b40a582497a6234eb752663a6306b">
<main data-route-view tabindex="-1">
<h1>工作台</h1>
</main>
</div>
const routes = new Map([
['/workspace', renderWorkspace],
['/workspace/settings', renderSettings]
]);
function matchRoute(url) {
return routes.get(url.pathname) ?? renderNotFound; }
3. 使用 pushState 提交导航
pushState 修改地址并新增历史记录,但不会自动加载页面,也不会触发 popstate。应用必须主动执行对应的渲染。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/5687b48cf61c04b9e0b75d455ec8aede8ace71f6">
<button type="button" data-open-settings>打开设置</button>
</div>
function navigate(path) {
const url = new URL(path, location.href);
if (url.origin !== location.origin) throw new Error('跨源路径');
history.pushState({
}, '', url);
return renderCurrentRoute();
}
4. 正确拦截站内链接
只处理正常左键点击、无修饰键、同源且路由器能够识别的链接。带 download、外部地址和非默认 target 的链接交给浏览器。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/76418c12ac0758d3987580462ce057d664688372">
<nav data-router-links>
<a href="/workspace/settings">账户设置</a>
<a href="/workspace" target="_blank">新窗口打开工作台</a>
</nav>
</div>
document.querySelector('[data-router-links]').onclick = e => {
const a = e.target.closest('a[href]');
if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const url = new URL(a.href);
if (a.hasAttribute('download') || (a.target && a.target !== '_self') || url.origin !== location.origin || !routes.has(url.pathname) || url.hash) return;
e.preventDefault(); void navigate(url.href);
};
5. 监听浏览器返回与前进
popstate 通知应用当前历史项发生切换。处理该事件时不要再次 pushState,否则返回操作会创建新的记录。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4759071e38859cf641eaf059b4a791d334cc119c">
<p role="status" data-navigation-state>当前位置</p>
</div>
window.addEventListener('popstate', () => {
void renderCurrentRoute(); });
6. 取消过时的路由数据请求
快速切换路由时,较早请求可能更晚返回。使用 AbortController 取消旧读取,同时通过独立请求标识过滤已经无法取消的结果。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1">
<section data-route-loading aria-live="polite">正在加载页面</section>
</div>
let active;
async function renderCurrentRoute() {
active?.abort();
const request = active = new AbortController();
try {
const view = await matchRoute(new URL(location.href))(request.signal);
if (active === request && !request.signal.aborted) mountView(view);
} catch (error) {
if (active === request && !request.signal.aborted) renderError(error);
}
}
7. 用 replaceState 保存当前历史项
筛选条件或滚动位置变化不一定需要新增历史记录。replaceState 可以替换当前记录,写入时保留其他模块已经存储的字段。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c0ec79cfc95bc481145d72a4e705799aa2e7cbcf">
<label>列表密度
<select name="density"><option>紧凑</option><option>舒展</option></select>
</label>
</div>
function saveScroll() {
history.replaceState({
...history.state, scrollY: window.scrollY }, '', location.href);
}
8. 恢复滚动位置
选择手动滚动恢复时,应在离开当前历史项前记录位置,并在新页面内容渲染完成后恢复。避免浏览器自动恢复与应用恢复互相竞争。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/fe110286a84374724bf24554b23aef731c10a2c7">
<section data-scroll-content>
<h2>历史文档</h2>
<ul data-document-list></ul>
</section>
</div>
history.scrollRestoration = 'manual';
function restorePosition(state) {
window.scrollTo({
top: Number.isFinite(state?.scrollY) ? state.scrollY : 0, behavior: 'instant' });
}
9. 导航后的焦点与标题
单页导航不会自动提供完整的新文档焦点体验。更新 document.title,并在合适时机将焦点移动到新页面主标题;返回操作应避免不必要的焦点抢占。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066">
<main data-page>
<h1 tabindex="-1" data-page-title>账户设置</h1>
<p>管理应用偏好。</p>
</main>
</div>
function announcePage(title) {
document.title = title;
document.querySelector('[data-page-title]')?.focus({
preventScroll: true });
}
10. 服务器刷新与异常处理
浏览器刷新会重新向服务器请求当前路径。客户端路由需要部署层正确处理已知路径,并保留静态资源与 API 的独立响应逻辑。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c67ad9feb927a1c3c728a53bd04418c3bf624e63">
<section role="alert" data-route-error>
<h2>页面加载失败</h2>
<button type="button" data-retry-route>重试</button>
</section>
</div>
验收时覆盖直接访问深层路径、连续返回、网络失败和滚动恢复。真实系统也要校验权限,客户端路由并不能代替服务端授权。
总结
History API 负责浏览器历史记录,路由匹配、数据加载和交互恢复则是应用职责。把这几个环节分离,可以减少导航过程中常见的历史污染、过期请求和页面状态丢失。
推荐阅读
React useReducer 实战:复杂组件状态转换与可测试的业务流程
https://github.com/tiktokwuyu-ux/technical-notes/commit/9230820adc2173383c177b3abd09fd51a5c65e47
React Suspense 实战:组件按需加载、错误边界与交互等待
https://github.com/tiktokwuyu-ux/technical-notes/commit/75af52f5c33999f7dc136f021f71bc9fe4a0e57d
Vue 3 插槽实战:作用域插槽、可复用表格与组件 API 设计
https://github.com/tiktokwuyu-ux/technical-notes/commit/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67
Next.js Route Handlers 实战:接口边界、参数校验与统一错误响应
https://github.com/tiktokwuyu-ux/technical-notes/commit/4f9a787a218b40a582497a6234eb752663a6306b
React useSyncExternalStore 实战:订阅外部数据源与稳定快照
https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066
Vite 工程化实战:环境变量、动态模块加载与多环境构建
https://github.com/tiktokwuyu-ux/technical-notes/commit/b79a134c126e9bd7f27da79f2a33bbad350b7ef1
原生 JavaScript 弹窗开发实战:Dialog、焦点管理与无障碍交互
https://github.com/tiktokwuyu-ux/technical-notes/commit/fe110286a84374724bf24554b23aef731c10a2c7
Vue Router 4 实战:导航守卫、权限路由与离开页面确认
https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1
SvelteKit load 实战:服务端数据读取、页面依赖与失效更新
https://github.com/tiktokwuyu-ux/technical-notes/commit/cc161de407f18c17088cb3532b8784fb6cbe3fe9
Angular Reactive Forms 实战:动态字段、交叉校验与复杂表单
https://github.com/tiktokwuyu-ux/technical-notes/commit/5687b48cf61c04b9e0b75d455ec8aede8ace71f6