前端路由笔记

前端路由的实现本质:检测URL变化,获取url地址,解析url匹配页面;
检测URL变化有两种方式: hash,HTML5 Historyhtml

  1. HTML5 History
    history.pushState 和 history.replaceState这两个api都分别接收三个参数:状态对象,标题, url(此url地址不支持跨域,跨域会报错)
    这两个API都会操做浏览器的历史记录,并不引发浏览器的刷新,pushState会增长一条新的历史记录,replaceState会替换当前的历史记录;
    popstate事件,须要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在作出浏览器动做时,才会触发该事件,如用户点击浏览器的回退按钮,或者在Javascript代码中调用3.back()。
    原理在点击某个路由时执行pushState,在操做浏览器时执行popstate;
  2. 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!!'));
相关文章
相关标签/搜索