跳到主要内容

如何用 JS 实现 H5 history 路由

H5 history

  • 用 url 规范的路由,但跳转时不刷新页面
  • history.pushState
  • window.onpopstate

正常页面浏览

改造成 H5 history 模式

演示下

<button id="btn">修改 url</button>
<script>
// 页面初次加载,获取 path
document.addEventListener('DOMContentLoaded', () => {
console.log('load', location.pathname) // load /test/test.html
})
// 打开一个新的路由
// 【注意】用 pushState 方式,浏览器不会刷新页面
document.getElementById('btn').addEventListener('click', () => {
const state = {name: 'page1'}
console.log('切换路由到', 'page1')
history.pushState(state, '', 'page1') // 重要 !!
})
// 监听浏览器前进,后退,观察浏览器 url 的变化
window.onpopstate = (e)=>{ // 重要 !!
console.log('onpopstate',e.state,location.pathname)
// 后端:onpopstate null /test/test.html
// 前进:onpopstate {name: "page1"} /test/page1
}
// 需要 server 端配合
</script>