spa---即单页面应用
意义:
a.前后端分离
b.减轻服务器压力
c.增强用户体验
d.Prerender预渲染 优化SEO //本身单页面对搜索引擎不友好,需要利用Prerender优化
工作原理:
要保证点击能跳转,浏览器返回能打开上一次打开的页面需要利用
history API或者hash API来实现
history 优雅,但是对浏览器有要求
<a class="api a">a.html</a>
<a class="api b">b.html</a>
<script type="text/javascript">
//注册路由
let tas=document.querySelectorAll('.api')
tas.forEach(item=>{
item.addEventListener("click",(e)=>{
e.preventDefault();
let link=item.textContent;
window.history.pushState({name:'api'},link,link) //接受三个参数,设置传入的参数 ,第二个是页面要显示的title,第三个是具体链接
},false);
})
window.addEventListener("popstate",(e)=>{
console.log({
location:location.href,
state:e.state
})
});
</script>
HASH不优雅,但是兼容性比较好
tas.forEach(item=>{
item.addEventListener("click",(e)=>{
e.preventDefault();
let link=item.textContent;
location.hash=link
},false)
})
window.addEventListener("hashchange",(e)=>{
console.log({
location:location.href,
hash:location.hash,
e
})
});