单页应用通过前端路由实现无刷新切换,核心是Hash和History两种模式。1. Hash模式利用URL中#后的部分变化触发hashchange事件,兼容性好但URL不美观;2. History模式使用pushState和replaceState API操作浏览器历史记录,配合popstate事件监听,可实现干净的URL路径,需服务端配置fallback以避免404。两者选择取决于浏览器兼容性、URL美观需求及服务端支持情况,理解其原理有助于掌握Vue Router、React Router等框架路由机制。

单页应用(SPA)之所以能实现页面无刷新切换,核心在于前端路由。它通过监听 URL 的变化,在不重新请求服务器的情况下动态加载对应视图内容。前端路由主要有两种实现方式:Hash 模式和 History 模式。
Hash 路由原理与实现
Hash 模式利用 URL 中的 # 后面的部分(即 hash 值)来模拟路由跳转。浏览器不会将 hash 部分发送给服务器,因此改变 hash 不会触发页面刷新,同时还会触发 hashchange 事件。
特点:
兼容性好,支持低版本浏览器URL 中带有 #,不够美观服务端无需特殊配置
手动实现示例:
立即学习“前端免费学习笔记(深入)”;
class HashRouter { constructor() { this.routes = {}; window.addEventListener('hashchange', () => { const path = location.hash.slice(1) || '/'; this.routes[path] && this.routes[path](); }); } on(path, callback) { this.routes[path] = callback; } push(path) { location.hash = path; }}// 使用const router = new HashRouter();router.on('/', () => console.log('首页'));router.on('/about', () => console.log('关于页'));
History 路由原理与实现
History 模式基于 HTML5 的 History API(如 pushState、replaceState)实现。它能使用真实的 URL 路径(如 /about),看起来更自然。
关键 API:
history.pushState(state, title, url):添加一条新记录,不刷新页面history.replaceState(state, title, url):替换当前记录popstate 事件:当用户点击前进/后退按钮时触发
手动实现示例:
立即学习“前端免费学习笔记(深入)”;
class HistoryRouter { constructor() { this.routes = {}; window.addEventListener('popstate', (e) => { const path = location.pathname; this.routes[path] && this.routes[path](e.state); }); } on(path, callback) { this.routes[path] = callback; } push(path, state = {}) { history.pushState(state, '', path); this.routes[path] && this.routes[path](state); } replace(path, state = {}) { history.replaceState(state, '', path); this.routes[path] && this.routes[path](state); }}// 使用const router = new HistoryRouter();router.on('/home', () => console.log('进入 home'));router.push('/home');
两种模式对比与选型建议
选择哪种模式取决于项目需求和部署环境。
Hash 模式适用场景:
需要兼容 IE9 等老旧浏览器项目部署在静态服务器上,无法配置回退路由对 URL 美观度要求不高
History 模式适用场景:
追求更友好的 URL 结构现代浏览器环境服务端可配合配置(如所有路径返回 index.html)
使用 History 模式时,服务端必须配置 fallback,确保所有前端路由路径都返回同一个 HTML 文件,否则直接访问会 404。
基本上就这些。理解前端路由的本质,有助于更好地掌握 Vue Router、React Router 等框架级路由工具的底层逻辑。
以上就是前端路由原理与Hash、History模式实现_js单页应用的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1537924.html
微信扫一扫
支付宝扫一扫