H5 路由的两种实现

1、原理浅析

  • hash模式
    如果a标签的href属性以"#"开头,那么当点击这个a标签时就会触发hashchange事件,在该事件处理函数中可以做很多事,比如发ajax请求,进行DOM操作替换页面等。
  • history模式
    hisroty模式相比hash模式,是一种比较新的路由模式,其浏览器兼容性如下:
pushState浏览器兼容性

原理就是利用history.pushState(state,null,url)更新浏览器url地址,这会触发 popstate 事件

2、具体实现

Talk is easy,show you the Code!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hash Test</title>
</head>
<body>
    <a href="#1">#1</a>
    <a href="#2">#2</a>
    <div id="content"></div>
    <script type='text/js-template' class="test" id="1">第一页</script>
    <script type='text/js-template' class="test" id="2">第二页</script>
    <script type="text/javascript">
        //1、选取元素
        var aElm=document.getElementsByTagName('a');
        var array=[].slice.call(aElm)
        var content=document.getElementById('content')
        //2、特性检测,如果支持history模式就用history,否则用hash模式
        if (history&&history.pushState) {
            window.addEventListener('popstate',handlePage);
            //劫持a元素的click事件,主要是为了更新history.state的状态以及替换url,当点击url跳转时先执行onclick再触发popstate
            array.forEach(function(v){
                v.onclick=function(event){
                    var path=event.target.hash.split("#")[1];
                    var newUrl=location.href.split('#')[0]+'\/'+path;
                    history.pushState({current:path},null,newUrl)
                }
            })
        } else {
            window.addEventListener('hashchange',handlePage);
        }
             //3、统一使用handlePage作为两种模式的事件处理器
        function handlePage(){
            if (history&&history.pushState) {
                var current=history.state&&history.state.current||'1';
                render(current)
            } else {
                var hash=location.hash||'#1';
                render(hash,true)
            }
            function render(selector,isHashMode){
                var hashMode=isHashMode&&true;
                var select='';
                if (hashMode) {
                    select=selector.split('#')[1];
                } else {
                    select=selector||history.state.current
                }
                var toPage=document.getElementById(select);
                content.innerHTML=toPage.innerHTML;
            }
        }
        handlePage();
    </script>
</body>
</html>

3、需要注意的地方

  • pushState的第三个参数url是不能跨域的
  • 纯粹的用JS调用pushState并不能触发popstate事件,只有浏览器的前进返回或者用户点击页面操作才能触发popstate。若想监听到所有的 pushState,则可以采用自定义事件的方法:
//创建全局事件
var _wr = function(type) {
   var orig = history[type];
   return function() {
       var rv = orig.apply(this, arguments);
      var e = new Event(type);
       e.arguments = arguments;
       window.dispatchEvent(e);
       return rv;
   };
};
//重写方法
 history.pushState = _wr('pushState');
 history.replaceState = _wr('replaceState');
//实现监听
window.addEventListener('replaceState', function(e) {
  console.log('THEY DID IT AGAIN! replaceState 111111');
});
window.addEventListener('pushState', function(e) {
  console.log('THEY DID IT AGAIN! pushState 2222222');
});
  • history 模式刷新页面无效问题(webpack设置 publicPath 必须为绝对路径才行)
location /{
    index  index.html index.htm;
    if (!-e $request_filename) {
        rewrite ^/(.*) /index.html last;
        break;
    }
}

参考:单页面应用路由实现原理:以 React-Router 为例

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容