SPA 前端路由原理与实现方式
一般 SPA 中前端路由有2中实现方式,本文会简单快速总结这两种方法及其实现:javascript
- 修改 url 中 Hash
- 利用 H5 中的 history
Hash
咱们都知道 url 中能够带有一个 hash, 好比下面 url 中的 page2
css
https://www.abc.com/index.html#page2
window 对象中有一个事件是 onhashchange,如下几种状况都会触发这个事件:html
- 直接更改浏览器地址,在最后面增长或改变#hash;
- 经过改变location.href或location.hash的值;
- 经过触发点击带锚点的连接;
4)浏览器前进后退可能致使hash的变化,前提是两个网页地址中的hash值不一样。前端
这个事件有 2 个重要的属性:oldURL 和 newURL,分别表示点击先后的 urljava
<!-- 该页面路径为 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>
这样咱们能够这样创建一个 DOMcss3
<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, 比较重要的样式已经在代码里标出来了。git
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 操做咱们借助 jQuerygithub
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点:
- 当 pushState 执行一个浏览器的 url 会发生变化,而页面不会刷新,只有当触发的前进后退等事件浏览器才会刷新;
- 这里的 url 是受到同源策略限制的,防止恶意脚本模仿其余网站 url 用来欺骗用户。因此当违背同源策略时将会报错;
- 火狐目前会忽略 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'); });
最后,关于两种方法有一些比较重要的特性总结一下:
- 有的文章提到“Firfox,Chrome在页面首次打开时都不会触发popstate事件,可是safari会触发该事件”,经实测如今的 safari 不存在这个问题。
- Mozilla指出,在 popstate 事件中,
e.originalEvent.state
属性是存在硬盘里的,触发该事件后读取的历史栈信息是经过 pushState 或 replaceState 写入的才会有值,不然改属性为 null。 -
history.state
和e.originalEvent.state
殊途同归,并且前者能够在该事件以外任何地方随时使用。 - 因为 pushSate, onpopstate 属于 H5 的部分,存在必定兼容问题,可使用 History.js (Github) 的 polyfill 解决这个问题。