前端路由笔记

本文深入探讨了前端路由的实现原理,包括HTML5 History API的使用,pushState和replaceState方法的操作,以及hash监听机制。通过具体代码示例展示了如何构建一个简单的前端路由系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  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!!'));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值