前端路由的实现本质:检测URL变化,获取url地址,解析url匹配页面; 检测URL变化有两种方式: hash,HTML5 HistoryHTML5 History history.pushState 和 history.replaceState这两个api都分别接收三个参数:状态对象,标题, url(此url地址不支持跨域,跨域会报错) 这两个API都会操作浏览器的历史记录,并不引起浏览器的刷新,pushState会增加一条新的历史记录,replaceState会替换当前的历史记录; popstate事件,需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮,或者在Javascript代码中调用3.back()。 原理在点击某个路由时执行pushState,在操作浏览器时执行popstate;hash location.hash window.location修改hash至不会引起页面刷新,而是当作新页面加到历史记录中。hash值变化会触发hashchange事件。Function Router(){ this.currentUrl = ‘’; this.routes = {};}Router.prototype.route = function(url, callback){ this.routes[url] = callback || function(){}}Router.prototype.refresh = function(){ this.currentUrl = location.hash.slice(1) || ‘/’; this.routesthis.currentUrl;}Router.prototype.init = function(){ window.addEventListener(’load’, this.refresh.bind(this), false); window.addEventListener(‘hashchange’, this.refresh.bind(this), false);}//使用var $target = $(’#target’);var route = new Router();route.init();route.route(’/’, $target.html(’this is index page!!’) );route.route(’/page1’, $target.html(’this is page1!!’));