hash定义

hash这个玩意是地址栏上#及后面部分,代表网页中的一个位置,#后面部分为位置标识符。页面打开后,会自动滚动到指定位置处。

位置标识符 ,一是使用锚点,比如<a name="demo"></a>,二是使用id属性,比如 <span id="demo" ></span>

带hash的请求

当打开http://www.example.com/#print服务器实际收到的请求地址是http://www.example.com/,是不带hash值的。

那么你真想带#字符咋办,转义啊, #转义字符为%23。也许有人会说,我咋知道这个转义啊,呵呵哒encodeURIComponent。

hashchange事件

The HashChangeEvent interface可以看到hashchange事件的参数HashChangeEvent继承了Event,仅仅多了两个属性

  • oldURL 先前会话历史记录的URL
  • newURL 当前会话历史记录的URL

    简单的调用方式,

    ```js

    window.onhashchange = function(e){

    console.log('old URL:', e.oldURL)

    console.log('new URL', e.newURL)

    }

[hash | CAN I USE](https://caniuse.com/#search=hash) 上可以看到除了IE8一下和那个尴尬的Opera Mini,hashchange事件都是支持得很好。那么怎么做到兼容,用MDN的代码做个引子js

;(function(window) {

// exit if the browser implements that event

if ("onhashchange" in window) { return; }

var location = window.location,

oldURL = location.href,

oldHash = location.hash;

// check the location hash on a 100ms interval

setInterval(function() {

var newURL = location.href,

newHash = location.hash;

// if the hash has changed and a handler has been bound...
if (newHash != oldHash && typeof window.onhashchange === "function") {
  // execute the handler
  window.onhashchange({
    type: "hashchange",
    oldURL: oldURL,
    newURL: newURL
  });

  oldURL = newURL;
  oldHash = newHash;
}

}, 100);

})(window);

```

hash history 简单版本实现

从上面可以得知,我们的实现思路就是监听hashchange事件,这里先抛开兼容性问题。

1 首先监听hashchange事件,定义个RouterManager函数

  • bind(this)让函数this指向RouterManager实例
  • 取到oldURL和newURL,同时查找一下是否注册,然后加载相关路由

    function RouterManager(list, index) {
        if (!(this instanceof RouterManager)) {
            return new RouterManager(arguments)
        }
        this.list = {} || list
        this.index = index
        this.pre = null
        this.current = null
    
        win.addEventListener('hashchange', function (ev) {
            var pre = ev.oldURL.split('#')[1],
                cur = ev.newURL.split('#')[1],
                preR = this.getByUrlOrName(pre),
                curR = this.getByUrlOrName(cur)
    
            this.loadWithRouter(curR, preR)
    
        }.bind(this))
    }

    2 定义添加,删除,加载,和初始化等方法

  • add的时候,判断是不是string, 如果是,重新构造一个新的router实例配置
  • load这里主要是用来还原直接输入带hash的地址,比如 http://ex.com/#music
  • loadWithRouter是最终渲染的入口
  • getByUrlOrName,你可以通过名字和path查找路由,name是方便日后扩展
  • setIndex设置默认路由地址
  • go, back, forward同history的方法
  • init里面会检测地址是不是带hash,然后走不通的逻辑。history.replaceState这是因为,如果不这么做, http://ex.com/跳转到http://ex.com/#/music会产生两条历史记录,这是我们不期望的。

    RouterManager.prototype = {
        add: function (router, callback) {
            if (typeof router === 'string') {
                router = {
                    path: router,
                    name: router,
                    callback: callback
                }
            }
            this.list[router.name || router.path] = router
        },
        remove: function (name) {
            delete this.list[name]
        },
        get: function (name) {
            return this.getByUrlOrName(name)
        },
        load: function (name) {
            if (!name) {
                name = location.hash.slice(1)
            }
            var r = this.getByUrlOrName(name)
            this.loadWithRouter(r, null)
        },
        loadWithRouter(cur, pre) {
            if (cur && cur.callback) {
                this.pre = this.current || cur
                cur.callback(cur, pre)
                this.current = cur
            } else {
                this.NOTFOUND('未找到相关路由')
            }
        },
        getByUrlOrName: function (nameOrUrl) {
            var r = this.list[nameOrUrl]
            if (!r) {
                r = Object.values(this.list).find(rt => rt.name === nameOrUrl || rt.path === nameOrUrl)
            }
            return r
        },
        setIndex: function (nameOrUrl) {
            this.indexRouter = this.getByUrlOrName(nameOrUrl)
        },
        go: function (num) {
            win.history.go(num)
        },
        back: function () {
            win.history.back()
        },
        forward: function () {
            win.history.forward()
        },
        init: function () {
            // 直接输入是带hash的地址,还原
            if (win.location.hash) {
                /* 模拟事件
                var ev = document.createEvent('Event')
                ev.initEvent('hashchange', true, true)
                ev.oldURL = ev.newURL = location.href
                win.dispatchEvent(ev) */
                this.load()
            } else if (this.indexRouter) { // 是不带hash的地址,跳转到指定的首页
                if ('replaceState' in win.history) {
                    // 替换地址
                    win.history.replaceState(null, null, win.location.href + '#' + this.indexRouter.path)
                } else {
                    win.location.hash = this.indexRouter.path
                }
            }
        }
    }

    3 公布函数

    RouterManager.prototype.use = RouterManager.prototype.add
    win.Router = RouterManager

4 页面怎么配置,简单的利用a标签href

<ul>
    <li>
        <li>
            <a href="#/m1">菜单1</a>
        </li>
        <ul>
            <li>
                <a href="#/m11">菜单11</a>
            </li>
            <li>
                <a href="#/m12">菜单12</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="#/m2">菜单2</a>
    </li>
    <li>
        <a href="#/m3">菜单3</a>
    </li>
</ul>

5 注册,当然你也可以通过选择器批量注册

var router = new Router()
router.NOTFOUND = function (msg) {
    content.innerHTML = msg
}
router.use('/m1', function (r) {
    req(r.path.slice(1))
})
router.use('/m11', function (r) {
    req(r.path.slice(1))
})
router.use('/m12', function (r) {
    req(r.path.slice(1))
})
router.use('/m2', function (r) {
    req(r.path.slice(1))
})
router.use('/m3', function (r) {
    req(r.path.slice(1))
})
router.setIndex('/m1')
router.init()

为了方便演示,定义req,ajax方法,模拟ajax请求

function req(url) {
    ajax(url, function (res) {
        content.innerHTML = res
    })
}

function ajax(id, callback) {
    callback(
        {
            'm1': '菜单1的主区域内容',
            'm11': '菜单11的主区域内容',
            'm12': '菜单12的主区域内容',
            'm2': '菜单2的主区域内容',
            'm3': '菜单3的主区域内容'
        }[id] || '404 Not Found!')
}

6 demo地址

hash-Router1.0

7 源码地址

简单的前端hash路由

8 下一步

这就成了最简单最基本的路由了。让然还有很多要考虑,比如如下

  1. 动态路由匹配
  2. 嵌套路由
  3. 重定向和别名
  4. 错误捕捉
  5. 生命周期钩子
  6. 等等等

hash | CAN I USE

The HashChangeEvent interface

onhashchange | MDN

window.location.hash 使用说明

JS单页面应用实现前端路由(hash)

Ajax保留浏览器历史的两种解决方案(Hash&Pjax)

理解浏览器的历史记录

理解浏览器历史记录(2)-hashchange、pushState

Web开发中 前端路由 实现的几种方式和适用场景

自己动手写一个前端路由插件

vue-router

react-router

简单的基于hash和hashchange的前端路由的更多相关文章

  1. SPA中前端路由基本原理与实现方式

    SPA 前端路由原理与实现方式 通常 SPA 中前端路由有2中实现方式,本文会简单快速总结这两种方法及其实现: 修改 url 中 Hash 利用 H5 中的 history Hash 我们都知道 ur ...

  2. 基于hash和pushState的网页前端路由实现

    客户端路由 对于客户端(通常为浏览器)来说,路由的映射函数通常是进行一些DOM的显示和隐藏操作.这样,当访问不同的路径的时候,会显示不同的页面组件.客户端路由最常见的有以下两种实现方案:* 基于Has ...

  3. 前端路由hash、history原理及简单的实践下

    阅读目录 一:什么是路由?前端有哪些路由?他们有哪些特性? 二:如何实现简单的hash路由? 三:如何实现简单的history路由? 四:hash和history路由一起实现 回到顶部 一:什么是路由 ...

  4. 前端路由以及浏览器回退,hash & history & location

    一.前言 其实不止一次想监听浏览器的回退方法,比如 在 list.html 页滚动加载了几页列表,点到 detail.html 看详情,反回来时又得重新加载几页 H5 有背景音乐的,跳页就得重新放,体 ...

  5. 前端路由两种模式:hash、history

    随着 ajax 的使用越来越广泛,前端的页面逻辑开始变得越来越复杂,特别是spa的兴起,前端路由系统随之开始流行. 从用户的角度看,前端路由主要实现了两个功能(使用ajax更新页面状态的情况下): 记 ...

  6. 前端路由的两种模式: hash 模式和 history 模式

    随着 ajax 的使用越来越广泛,前端的页面逻辑开始变得越来越复杂,特别是spa的兴起,前端路由系统随之开始流行. 从用户的角度看,前端路由主要实现了两个功能(使用ajax更新页面状态的情况下): 记 ...

  7. 前端路由的两种模式:hash(#)模式和history模式(转)

    随着 ajax 的使用越来越广泛,前端的页面逻辑开始变得越来越复杂,特别是spa的兴起,前端路由系统随之开始流行. 从用户的角度看,前端路由主要实现了两个功能(使用ajax更新页面状态的情况下): 记 ...

  8. 从零开始搭建一个简单的基于webpack的vue开发环境

    原文地址:https://segmentfault.com/a/1190000012789253?utm_source=tag-newest 从零开始搭建一个简单的基于webpack的react开发环 ...

  9. 前端路由原理之 hash 模式和 history 模式

    什么是路由? 个人理解路由就是浏览器 URL 和页面内容的一种映射关系. 比如你看到我这篇博客,博客的链接是一个 URL,而 URL 对应的就是我这篇博客的网页内容,这二者之间的映射关系就是路由. 其 ...

随机推荐

  1. 项目实战12.2—企业级监控工具应用实战-zabbix操作进阶

    无监控,不运维.好了,废话不多说,下面都是干货. 流量党勿入,图片太多!!! 项目实战系列,总架构图 http://www.cnblogs.com/along21/p/8000812.html 一.U ...

  2. MySQL 导入外部数据时报错:1153: Got a packet bigger than 'max_allowed_packet' 解决方案

    MySQL 导入外部数据时报错:1153: Got a packet bigger than 'max_allowed_packet' 解决方案 zoerywzhou@163.com http://w ...

  3. intellij idea 主题大全,看不惯idea 那2种主题的来这里了

    一直用默认的主题,但是白色的背景看久了会晃眼睛.所以打算换成黑色的. 不过Intellij只有两种主题,Default和Darcula. 现在只能自己手动安装一个了.新主题需要满足, 看久了不会太累. ...

  4. C# 接口使用方法

    之前一直不理解接口这一概念,今天无意中翻书,网上查资料悟道其中的道理,现在工作没有用到interface这一块,怕以后会遇到忘记实现的方法便记录下来,哪里写的不对希望读者指出,话不多说,接下来看我对接 ...

  5. Structured Streaming从Kafka 0.8中读取数据的问题

    众所周知,Structured Streaming默认支持Kafka 0.10,没有提供针对Kafka 0.8的Connector,但这对高手来说不是事儿,于是有个Hortonworks的邵大牛(前段 ...

  6. IP地址简介

    IP地址 IP地址,Internet Protocol Address,网络协议地址: IP地址与网络接口绑定,并不是指向一台主机,一个主机可能有多个IP地址,如果其连接多个网络,有多个网络接口: I ...

  7. 【python】input、int、if-else、注释、while、module(random.randint())语法示例

    import random luckyNum=random.randint(2,9) i=1 while i<=3: guessNum=input("请你猜猜我的幸运号码:" ...

  8. DeepLearning.ai学习笔记(四)卷积神经网络 -- week1 卷积神经网络基础知识介绍

    一.计算机视觉 如图示,之前课程中介绍的都是64* 64 3的图像,而一旦图像质量增加,例如变成1000 1000 * 3的时候那么此时的神经网络的计算量会巨大,显然这不现实.所以需要引入其他的方法来 ...

  9. 如何检测mvc性能和sql语句

    mvc中使用linq如何检测sql语句 .net中使用mvc开发已经是一种趋势,不仅仅是.net ,java 等越来越多的开发者更倾向于mvc这种开发模式,在.net mvc 使用linq非常方便,各 ...

  10. vue入坑总结

    1.Do not mount Vue to <html> or <body> - mount to normal elements instead. Vue2.x之后不推荐挂载 ...