SPA 前端路由原理与实现方式

通常 SPA 中前端路由有2中实现方式,本文会简单快速总结这两种方法及其实现:

  1. 修改 url 中 Hash
  2. 利用 H5 中的 history

Hash

我们都知道 url 中可以带有一个 hash, 比如下面 url 中的 page2

https://www.abc.com/index.html#page2

window 对象中有一个事件是 onhashchange,以下几种情况都会触发这个事件:

  1. 直接更改浏览器地址,在最后面增加或改变#hash;
  2. 通过改变location.href或location.hash的值;
  3. 通过触发点击带锚点的链接;

4)浏览器前进后退可能导致hash的变化,前提是两个网页地址中的hash值不同。

这个事件有 2 个重要的属性:oldURL 和 newURL,分别表示点击前后的 url

<!-- 该页面路径为 https://www.abc.com/index.html -->

<a href="#page2">click me</a>
<script type="text/javascript">
window.onhashchange = function(e){
console.log(e.oldURL); //https://www.abc.com/index.html
console.log(e.newURL); //https://www.abc.com/index.html#page2
}
</script>

这样我们可以这样建立一个 DOM

  <nav>
<a class="item active" href="#page1" data-target="#index">page1</a>
<a class="item" href="#page2" data-target="#info">page2</a>
<a class="item" href="#page3" data-target="#detail">page3</a>
<a class="item" href="#page4" data-target="#show">paga4</a>
<a class="item" href="#page5" data-target="#contact">paga5</a>
</nav>
<div class="container">
<div class="page active" id="index">
<h1>This is index page</h1>
</div>
<div class="page" id="info">
<h1>This is info page</h1>
</div>
<div class="page" id="detail">
<h1>This is detail page</h1>
</div>
<div class="page" id="show">
<h1>This is show page</h1>
</div>
<div class="page" id="contact">
<h1>This is contact page</h1>
</div>
</div>

为了好看我们加上 css, 比较重要的样式已经在代码里标出来了。

body{
padding:0;
margin: 0;
}
h1{
margin: 0 0 0 160px;
}
nav{
width: 150px;
height: 150px;
float: left;
}
nav a{
display: block;
background: #888;
border: 1px solid #fff;
border-top: none;
width: 150px;
font-size: 20px;
line-height: 30px;
text-align: center;
color: #333;
text-decoration: none;
}
.container{
height: 154px;
}
/* page 部分比较重要*/
.page{
display: none;
}
.page.active{
display: block;
}
/* page 部分比较重要*/
nav a.active, .container{
background: #ddd;
border-right-color: #ddd;
}

重点是下面的 javascript,这里 DOM 操作我们借助 jQuery

  var containers = $('.container');
var links = $('.item'); window.onhashchange = function(e){
var currLink = $('[href="'+ location.hash + '"]').eq(0);
var target = currLink.attr('data-target'); currLink.addClass('active').siblings('a.item').removeClass('active');
$(target).addClass('active').siblings('.page').removeClass('active');
}

实现的逻辑不难,但是利用 hash 总是没有所谓前端路由的那种味,必然也不是主流方法。同样的效果如果需求简单不考虑兼容性的话,利用 css3 中 target 伪类就可以实现,这不是本文的重点,这里就不展开了。

history

作为一种主流方法,我们下面看看 history 如何实现。

history 其实浏览器历史栈的一个借口,去过只有 back(), forward(), 和 go() 方法实现堆栈跳转。到了 HTML5 , 提出了 pushState() 方法和 replaceState() 方法,这两个方法可以用来向历史栈中添加数据,就好像 url 变化了一样(过去只有 url 变化历史栈才会变化),这样就可以很好的模拟浏览历史和前进后退了。而现在的前端路由也是基于这个原理实现的。

这里我们先简单认识一下 history:

go(n) 方法接受一个整数参数, n大于0会发生前进 n 个历史栈页面; n小于0会后退 -n 个历史栈页面;

forward() 前进一个页面

back() 后退一个页面

  • 以上三个方法会静默失败

pushSate(dataObj, title, url) 方法向历史栈中写入数据,其第一个参数是要写入的数据对象(不大于640kB),第二个参数是页面的 title, 第三个参数是 url (相对路径)。这里需要说明的有3点:

  1. 当 pushState 执行一个浏览器的 url 会发生变化,而页面不会刷新,只有当触发的前进后退等事件浏览器才会刷新;
  2. 这里的 url 是受到同源策略限制的,防止恶意脚本模仿其他网站 url 用来欺骗用户。所以当违背同源策略时将会报错;
  3. 火狐目前会忽略 title 参数

replaceState(dataObj, title, url) 这个和上一个的区别就在于它不是写入而是替换栈顶记录,其余和 pushState 一模一样

History 还有1个静态只读属性:

History.length:当然历史堆栈长度

  • 还有的都是已经废除的老古董了,这里就不提了

了解了这么多,那么可以研究一下如何利用 history 实现一个前端路由了,这里只考虑 javascript 部分,css 部分和上文一致。这里我们修改部分 html:

<a class="item active" href="/page1.html" data-target="#index">page1</a>
<a class="item" href="/page2.html" data-target="#info">page2</a>
<a class="item" href="/page3.html" data-target="#detail">page3</a>
<a class="item" href="/page4/subpage1.html" data-target="#show">paga4-1</a>
<a class="item" href="/page5/subpage2.html" data-target="#contact">paga4-2</a>

我们修改了 a 标签的 href,这样的链接看上去才不是锚点了,不过这个过程我们要处理比较多的工作。首先为了简单一些,我们的这里仅仅对 .html 或没有扩展名结尾的链接设置前端路由:

// 通过委托的方法组织默认事件
var routerRxp = /\.html$|\/[^.]*$|/;
$(document).click(function(e){
var href = e.target.getAttribute('href');
if(href && routrRxp.test(href)){
e.preventDefault();
}
});

而后我们在点击时把数据写入历史栈,并控制 class 效果:

$(document).click(function(e){
var href = e.target.getAttribute('href'); if(href && routerRxp.test(href)){
var id = e.target.getAttribute('data-target');
history.pushState({targetId: id}, 'History demo', href);
$(id).addClass('active').siblings('.page').removeClass('active');
e.preventDefault();
}
});

到这里,链接就可以点击了,但是浏览器的前进后退还不能用,我们加入 onpopstate 事件:

$(window).on('popstate',function(e){
var id = e.originalEvent.state.targetId;
$(id).addClass('active').siblings('.page').removeClass('active');
});

这样前进后退就可以用了,但是我们发现这样并不能退回主页,因为我们的主页默认就是 page1 标签页,所以没有为主页添加 state,简单处理就让其自己刷新好啦:

var indexPage = location.href;
$(window).on('popstate',function(e){
if(location.href === indexPage){
location.reload();
}
var id = e.originalEvent.state.targetId;
$(id).addClass('active').siblings('.page').removeClass('active');
});

注意,这里不能使用重置 location.href 的方法刷新,那样就不能再前进了。

下面附上 history 方法的完整 js 代码

var indexPage = location.href;
var routerRxp = /\.html$|\/[^.]*$|/;
$(document).click(function(e){
var href = e.target.getAttribute('href'); if(href && routerRxp.test(href)){
var id = e.target.getAttribute('data-target');
history.pushState({targetId: id}, 'History demo', href);
$(id).addClass('active').siblings('.page').removeClass('active');
e.preventDefault();
}
}); $(window).on('popstate',function(e){
if(location.href === indexPage){
location.reload();
}
var id = e.originalEvent.state.targetId;
$(id).addClass('active').siblings('.page').removeClass('active');
});

最后,关于两种方法有一些比较重要的特性总结一下:

  1. 有的文章提到“Firfox,Chrome在页面首次打开时都不会触发popstate事件,但是safari会触发该事件”,经实测现在的 safari 不存在这个问题。
  2. Mozilla指出,在 popstate 事件中,e.originalEvent.state 属性是存在硬盘里的,触发该事件后读取的历史栈信息是通过 pushState 或 replaceState 写入的才会有值,否则改属性为 null。
  3. history.statee.originalEvent.state 异曲同工,而且前者可以在该事件之外任何地方随时使用。
  4. 由于 pushSate, onpopstate 属于 H5 的部分,存在一定兼容问题,可以使用 History.js (Github) 的 polyfill 解决这个问题。

最新文章

  1. 读 [The Root of Lisp]
  2. Norm and Sparse Representation
  3. muduo简化(1):Reactor的关键结构
  4. script —— 终端里的记录器
  5. MySQL之常用函数
  6. Less注释语法
  7. Spring之Bean的基本概念
  8. python3学习笔记十六
  9. Asp.Net Core 程序部署到Linux(centos)生产环境(一):普通部署
  10. Servlet.service() for servlet [jsp] in context with path [/Healthy_manager] threw exception [Unable to compile class for JSP] with root cause java.lang.IllegalArgumentException: Page directive: inval
  11. Velocity 快捷键
  12. v4l2功能列表大全【转】
  13. DataSet 读取xml 报错有非法字符
  14. 转战JS(1) 初探与变量类型、运算符、常用函数与转换
  15. 洛谷P2114 [NOI2014]起床困难综合症
  16. HGOI20180812 (NOIP2018 提高组 Day1 模拟试题)
  17. Tomcat访问日志浅析 (转)
  18. UVA-127 &quot;Accordian&quot; Patience (模拟)
  19. Undirected Graphs
  20. Eclipse如何定位到某一个类所在硬盘上的位置

热门文章

  1. Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionExcep linux下mysql修改连接超时wait_timeout修改后就ok了
  2. mysql按表字段内容长度排序
  3. MySQL的详细操作
  4. js正则表达式常用的大部分函数
  5. 《时间线》:WWT 数字宇宙,虚拟星空
  6. linux中用户和用户组的概念以及查看命令
  7. Linux(Centos7.X ) 配置Java 环境变量
  8. 一个类似ThinkPHP的Node.js框架——QuickNode
  9. [洛谷P4549] [模板] 裴蜀定理
  10. VMware虚拟机克隆CentOS6.5后修改网卡