前端路由的完成实质:检测URL变化,猎取url地点,剖析url婚配页面;
检测URL变化有两种体式格局: hash,HTML5 History
- HTML5 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.routes[this.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!!'));