前端路由实现

有很长一段时间没有更新博客了,近一段时间开始重新梳理知识点和写博客了。重要的事情说三遍,新的博客地址:欢迎访问,新的博客地址:欢迎访问,新的博客地址:欢迎访问

在单页应用上,前端路由并不陌生。单页应用是指在浏览器中运行的应用,在使用期间页面不会重新加载。
基本原理:以 hash 形式(也可以使用 History API 来处理)为例,当 url 的 hash 发生改变时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。
基于hash的前端路由优点是:能兼容低版本的浏览器。
history 是 HTML5 才有的新 API,可以用来操作浏览器的 session history (会话历史)。
从性能和用户体验的层面来比较的话,后端路由每次访问一个新页面的时候都要向服务器发送请求,然后服务器再响应请求,这个过程肯定会有延迟。而
前端路由
在访问一个新页面的时候仅仅是变换了一下路径而已,没有了网络延迟,对于用户体验来说会有相当大的提升。
Demo:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>前端路由实现</title>
    <style type="text/css">
        *{
            margin: 0;
            padding:0;
        }
        a{
            list-style: none;
            text-decoration: none;
            color: #fff;
        }
        ul{
            width: 500px;
            margin: 100px auto;
        }
        li{
            padding:5px;
            display: inline-block;
            background-color: #000;
        }
    </style>
</head>
<body>
<ul>
    <li><a href="#/">turn white</a></li>
    <li><a href="#/red">turn red</a></li>
    <li><a href="#/yellow">turn yellow</a></li>
</ul>
<script type="text/javascript" src="router.js"></script>
<script type="text/javascript">
var content = document.querySelector('body');
function changeBgColor(color) {
    content.style.backgroundColor = color;
}
Router.route('/', function() {
    changeBgColor('white');
});
Router.route('/red', function() {
    changeBgColor('red');
});
Router.route('/yellow', function() {
    changeBgColor('yellow');
});
</script>
</body>
</html>

router.js

//构造函数
function Router() {
    this.routes = {};
    this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
    this.routes[path] = callback || function(){};//给不同的hash设置不同的回调函数
};
Router.prototype.refresh = function() {
    console.log(location.hash.slice(1));//获取到相应的hash值
    this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
    // console.log(this.currentUrl);
    this.routes[this.currentUrl]();//根据当前的hash值来调用相对应的回调函数
};
Router.prototype.init = function() {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}
//给window对象挂载属性
window.Router = new Router();
window.Router.init();

上面路由系统 Router 对象实现,主要提供三个方法:

  • init 监听浏览器url hash更新事件
  • route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
  • refresh 执行当前url对应的回调函数,更新页面

Router 调用方式以及呈现效果如下:点击触发 url 的 hash 改变,并对应地更新内容(这里为 body 背景色)

相关博文学习:
从 React Router 谈谈路由的那些事
前端路由实现与 react-router 源码分析

正在学习中,待续。。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值