hash
hash模式原理是onhashchange事件,可以在window对象上监听这个事件:
window.onhashchange = function(event){
console.log(event)
let hash = location.hash.slice(1);
document.body.style.color = hash;
}
hash发生变化的url都会被浏览器记录下来,浏览器的前进后退都可以用。
网易云音乐,百度网盘都采用了hash路由
history
利用H5的 history中新增的两个API pushState() 和 replaceState() 和一个事件onpopstate监听URL变化
hash路由支持低版本的浏览器(能兼容到IE8),而history(兼容到IE10)路由是HTML5新增的API
history api可以分为两部分。切换和修改
切换历史状态
包括back,forward,go三个方法,对应浏览器的前进,后退,跳转。
history.go(-2); //后退两次
history.go(2); //前进两次
history.back(); //后退
history.forward(); //前进
修改历史状态 pushState() 和 replaceState()
history.pushState({color:"#999999"},'red','red')
window.onpopstate = function(event){
console.log(event)
if(event.state&& event.state.color === 'red'){
document.body.style.color = 'red';
}
}
history弊端:
如果点击刷新,就会重新向后端服务器发送请求,如果服务器中没有相应的响应资源,会到时出现404页面
如果想在github.io上搭建一个诶单页面博客,应该选择hash模式