SPA路由器开发手记-解决chrome下location.replace后,浏览器返回操作导致页面刷新的问题

我的路由器是参考的backbone和EXT5做的。其中history采用的hashchange的方式来进行监控,IE67不支持的问题可以参考司徒大这篇文章

我要说的是在chrome下通过location.replace替换完hash的时候,用户调用浏览器的后退操作,将导致页面刷新

相信backbone的用户也会有这个问题,我的解决方法是用history.replaceState的方式更新hash 就木有这个问题了

以下是我修改的backbone  history中的_updateHash方法

_updateHash: function(location, fragment, replace) {
  var me = this,
    hash
= '#' + fragment; if (replace) { //由于chrome下location.replace替换当前页后 进行返回操作会刷新页面
  //ff无辜受到牵连 同罚之 //所以我们这里采用replaceState的方式更新hash if ((typeof me.history.replaceState === 'function') && !me.iframe) { me.history.replaceState(me.history.state, '', hash); }
else { //先移除location中的锚点信息 var href = location.href.replace(/(javascript:|#).*$/, ''); //替换当前页 这么做不会产生浏览历史 location.replace(href + hash); } } else { // Some browsers require that `hash` contains a leading #. // 如果不是 则简单的location.hash='#xxxx' location.hash = hash; } }

  值得说一下的是backbone的Router非常非常薄,从URL Fragement->handler 映射的方式我觉得并不可取,人们常常抱怨路随着项目扩张由规则注册越来越膨胀很大一部分就是因为这个原因(另外一部分是路由规则的单一)。

  我的路由模块 是从URL Fragement->routeData的映射, 该模块由Router、Route,History三个部分组成,History就不说了 主要就是围绕hashchange进行的封装,Router主要是处理History的hashchange事件,在发生hashchange事件的时候 通过调用其中的Route一个一个对hash进行识别,如果能够匹配 则从hash中提取并返回routeData

原文地址:https://www.cnblogs.com/xmlsvg/p/3722669.html