前端路由思考
前言
其实路由就是把状态归于一种形式记录下来,不一定是hash跟history,当然常见的几种路由方式就是这几种。
那为什么常见的就是这几种了,首先兼容性高,而且给别人分享页面的时候是可以记录下来的,这就跟后端的路由一样了。
hash路由
一下一个简单的hash路由实现。
当然之后可能通过正则来写路由也是很简单的,加一个判断就好,接下来我们看看这个函数hashchange:

看文档的时候发现可以模拟,但是很损失性能。
|
|
history
HTML5有新的api,路由无非就是实现以下的功能:
- 前进后退
- url变化的监听
- url对应的状态
刚好HTML5的新api都能满足
The pushState() method:
pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let’s examine each of these three parameters in more detail:state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry’s state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user’s disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you’re encouraged to use sessionStorage and/or localStorage.
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you’re moving.
URL — The new history entry’s URL is given by this parameter. Note that the browser won’t attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it’s relative, it’s resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn’t specified, it’s set to the document’s current URL.
对应的监听状态的事件是:popstate跟hashchange差不多就不多说了。
总结
就我而言我感觉基于history的路由没有基于hashchange的方便,兼容性也比他好,可能history设计目的并不是用路由的吧。
