hash模式
URL的hash也就是锚点(#), 本质上是改变window.location的href属性.
我们可以通过直接赋值location.hash来改变href, 但是页面不发生刷新
history模式
history接口是HTML5新增的, 它有五种模式改变URL而不刷新页面.
- 通过window.history来处理url
- history在H5之前有go(),back(),forword()三个API,后来增加pushState(),replaceState()两个API
- history.back() 等价于 history.go(-1) history.forward() 则等价于 history.go(1)
history.pushState(state, title, url)
history.pushState()只会改变当前地址栏的路径,并不会更新页面内容,但会改变浏览历史记录。
- state:状态对象
- title:忽略,填null
- url:要跳转的地址
history.replaceState(state, title, url)
history.replaceState()就是把当前的历史记录改成目标路径,不会进行页面跳转和刷新,也不会增加浏览历史记录,但是如果按F5刷新,他会跳转到目标页面。
- state:状态对象
- title:忽略,填null
- url:要跳转的地址
window.onpopstate事件 监听如下操作
- 点击浏览器的前进按钮/后退按钮
- 执行js代码:history.go(n) / history.forward()
- 注意:pushstate()和replacestate()不会触发popstate事件
区别:
- hash兼容到IE8,history兼容到IE10。
- hash 本来是拿来做页面定位的,如果拿来做路由的话,原来的锚点功能就不能用了。
- hash 的传参是基于 url 的,如果要传递复杂的数据,会有体积的限制,而 history 模式不仅可以在url里放参数,还可以将数据存放在一个特定的对象中。