浏览器原生支持前端路由,需用history.pushState修改URL而不刷新,监听popstate处理前进后退,代理a标签点击拦截默认跳转,并配置服务端将非资源请求均返回index.html。
浏览器原生支持 history.pushState 和 hashchange,不需要框架也能实现前端路由——关键在于拦截导航、更新视图、同步 URL,同时避免页面刷新。
history.pushState 替代页面跳转直接调用 location.href = '/user' 会触发完整刷新;必须用 history.pushState 修改 URL 而不重载。它不触发 popstate,只影响地址栏和历史栈。
null),后续在 popstate 事件中能读取
第三个参数才是真实路径,必须是同源的相对路径(如 '/post/123'),不能是绝对 URLpushState 本身不做任何 DOM 操作history.pushState({ page: 'user' }, '', '/user');
// 此时 URL 变为 https://example.com/user,但页面未刷新
popstate 事件用户点击返回按钮或调用 history.back() 时,会触发 popstate,但仅当历史记录由 pushState 或 replaceState 创建时才触发——初始页面加载不会触发。
DOMContentLoaded 后绑定,否则可能漏掉首次进入时的状态event.state 是你传入 pushState 的状态对象,可用于快速判断路由意图location.pathname 解析当前路径popstate 里再调用 pushState,否则会无限循环window.addEventListener('popstate', (event) => {
const path = location.pathname;
if (path === '/user') renderUserPage();
else if (path === '/post') renderPostList();
});
用户点击 仍会刷新页面。必须全局代理点击事件,对同源的相对路径链接调用 preventDefault() 并手动路由。
document,避免漏掉动态插入的链接event.target.href 是否同源且为相对路径(可用 new URL(href).origin === location.origin 判断)history.pushState + 渲染,而非 location.assign
target="_blank"、download 或含 javascript: 的链接document.addEventListener('click', (event) => {
const link = event.target.closest('a[href]');
if (!link) return;
const url = new URL(link.href);
if (url.origin === location.origin && url.pathname !== location.pathname) {
event.preventDefault();
history.pushState({ path: url.pathname }, '', url.pathname);
navigateTo(url.pathname); // 自定义渲染函数
}
});
index.html
用户直接访问 https://site.com/dashboard 时,请求会发到服务端。如果服务端没配置,会返回 404 —— 因为实际没有 /dashboard 这个文件。
.js、.css、.png 等)都返回 index.html
historyApiFallback,但生产环境部署必须由服务端保证404 页面重定向,因为那是客户端行为,对直接访问无效最易被忽略的是:开发时一切正常,上线后深层路由全部 404。这不是 JS 写错了,是服务端没配好。