history.pushState无刷新改变url
通过history.pushState无刷新改变url
背景
在浏览器中改变地址栏url,将会触发页面资源的重新加载,这使得我们可以在不同的页面间进行跳转,得以浏览不同的内容。但随着单页应用的增多,越来越多的网站采用ajax来加载资源。因为异步加载的特性,地址栏上的资源路径没有被改变,随之而来的问题就是页面的状态无法被保存。这导致我们难以通过熟悉的方式(点击浏览器前进/后退按钮),在前后的页面状态间进行切换。
为了解决ajax页面状态不能返回的问题,人们想出了一些曲线救国的方法,比如利用浏览器hash的特性,将新的资源路径伪装成锚点,通过onhashchange
事件来改变状态,同时又避免了浏览器刷新。但这样始终显得有些hack。
现在HTML5规范为 window.history
引入了两个新api,pushState
和 replaceState
,我们可以使用它很方便的达到改变url不重载页面的目的。
表现
改变地址栏url,不刷新页面。
观察地址栏,可以看到当url路径由”join”改变为”login”时,页面状态也随之改变,但并没有造成背景图片等资源的重新加载。
此时”join”被压入历史栈,当点击浏览器后退按钮时仍然能够回到”join”状态。
使用
pushState
与replaceState
方法类似,都有改变当前地址栏URL的作用。主要区别在于pushState
会在浏览器中创建一条新的历史纪录,而replaceState
仅仅替换将当前地址为指定URL。
下面以pushState
接口为例:
API
history.pushState(state, title[, url]);
事件
执行history.back()
或history.forward()
后触发 window.onpopstate
事件
参数
state: 对象,可以存存放一些数据表示当前状态。当浏览器执行前进后退操作时触发onpopstate
事件,state将成为event
的子对象,可通过event.state
获取先前状态。但是注意state中的属性值不能为引用类型对象,会报ObjectCloneError
(对象克隆异常),例如允许{data:”test”},不允许{data:document.querySelector(‘#testId’)}。
title:目前无特殊意义,一般可以传入 document.title
或 ”(空字符串)。
url:要替换的url,如果是pushState
则会添加一条历史记录,不允许跨域。
示例
history.pushState({title:"login"}, "login", "fish/login");
window.addEventListener("popstate", function(event){
if(event.state) {
var state = event.state.title;
switch(state) {
case "login":.............;break;
case "join" :.............;break;
case "home" :.............;break;
}
}
}, false);
实例
下面以一个具体实例来展示pushState
的作用,注意地址栏的变化。
效果
两次点击白色圆环改变页面背景,将在当前浏览器历史会话(window.history
)中写入两条新记录:“/pushState.html?state=blue”和“/pushState.html?state=org”。
点击浏览器后退/前进按钮相当于执行history.back()
与history.forward()
方法,将触发onpopstate
事件,通过监听onpopstate
事件改变相应状态。
源代码
本实例在Chrome下编写调试,请在Chrome、Firefox、IE10+等现代浏览器中运行。
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="renderer" content="webkit" />
<head>
<title>pushState demo</title>
<style>
body {
font-family: "Microsoft YaHei";
transition: background-color .3s;
}
.bg-org {
color: #383c3c;
background-color: #FF6633;
}
.bg-blue {
color: #fbfaf5;
background-color: #6699FF;
}
.time {
margin-top: 20%;
text-align: center;
font-size: 4em;
font-weight: 100;
}
.switch {
margin: auto;
width: 30px;
height: 30px;
position:absolute;
bottom:25%;
left:0;
right:0;
cursor:pointer;
box-shadow: 0 0 0 5px rgba(255,255,255,.6);
border-radius: 50%;
transition: box-shadow .1s;
}
.switch:hover {
box-shadow: 0 0 0 5px rgba(255,255,255,.75);
}
.switch:active {
box-shadow: 0 0 0 30px rgba(255,255,255,.4);
}
</style>
</head>
<body class="bg-org">
<h1 id="time" class="time">Loading...</h1>
<div id="switch" class="switch"></div>
<script>
var time = $('#time');
function $(selector) {return document.querySelector(selector);}
// 显示当前时间
setInterval(function(){
var date = new Date(),
format = function(n) {return n<10?'0'+n:n};
time.innerHTML = format(date.getHours()) + ' : ' + format(date.getMinutes()) + ' : ' + format(date.getSeconds());
}, 500);
$('#switch').addEventListener('click', toggleState, false);
// 监听popstate事件
history.pushState && window.addEventListener("popstate", function(e) {
// 获取history.state对象中的状态信息
// 在这里state将自动成为event的子对象,可直接通过event.state访问
var flag = e.state && e.state.title;
$('body').className = flag || ($('body').className=='bg-org'?'bg-blue':'bg-org');
}, false);
function toggleState(e) {
var flag = $('body').className=='bg-org'?'bg-blue':'bg-org';
// 新建历史记录,将当前状态信息保存至history.state中
history.pushState && history.pushState({ title: flag }, flag, 'pushState.html?state='+flag.split('-')[1]);
$('body').className = flag;
}
</script>
</body>
</html>
更多
replaceState
前面曾说过,pushState
和replaceState
的区别在于pushState
会在浏览器中创建一条新历史纪录,而replaceState
仅替换当前地址。
我们将上面的实例稍作修改,观察replaceState
的具体表现。
替换history.pushState
为history.replaceState
:
history.pushState && history.replaceState({ title: flag }, flag, 'pushState.html?state='+flag.split('-')[1]);
对比运行结果可以看到,多次执行replaceState
仅改变当前地址栏的URL,而没有创建新的历史记录。
window.location
下面我们再使用传统的window.location
跳转,对比与pushState
的区别。
<script>
if(urlParam('state')=='blue') {
$('body').className = 'bg-blue';
} else {
$('body').className = 'bg-org';
}
var time = $('#time');
function $(selector) {return document.querySelector(selector);}
// 显示当前时间
setInterval(function(){
var date = new Date(),
format = function(n) {return n<10?'0'+n:n};
time.innerHTML = format(date.getHours()) + ' : ' + format(date.getMinutes()) + ' : ' + format(date.getSeconds());
}, 500);
$('#switch').addEventListener('click', toggleState, false);
function toggleState(e) {
var flag = $('body').className=='bg-org'?'bg-blue':'bg-org';
window.location = location.pathname + '?state=' + flag.split('-')[1];
$('body').className = flag;
}
/**
* 获取url参数
* @param {String} name 参数名
* @return {String} 参数值
*/
function getUrlParam(name){
var reg, value;
reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
value = window.location.search.substr(1).match(reg);
return value==null?null:decodeURI(value[2]);
}
</script>
可以看到使用传统location跳转将会造成页面重载,虽然在功能上能够达到同样的目的,但在用户体验上将大打折扣。
#hash
最后再来介绍另一种无刷新技巧window.location.hash
的使用。
URL中#称为位置的标识符,代表网页中的一个位置,当浏览器读取这个URL后,会自动将可视区域滚动至所定义的锚点处。HTTP请求中不包括#,也就是说改变#后的内容不会向服务器发起请求,因此也就不会引起页面重载。
window.location.hash这个属性可读可写。读取时,可以用来判断网页状态是否改变;写入时,则会在不重载网页的前提下,创造一条访问历史记录。
当#值发生变化时,就会触发onhashchange
事件。
<script>
var time = $('#time');
function $(selector) {return document.querySelector(selector);}
// 显示当前时间
setInterval(function(){
var date = new Date(),
format = function(n) {return n<10?'0'+n:n};
time.innerHTML = format(date.getHours()) + ' : ' + format(date.getMinutes()) + ' : ' + format(date.getSeconds());
}, 500);
// 监听onhashchange事件
window.addEventListener("hashchange", function(e) {
// 获取hash值判断页面状态
var flag = location.hash && location.hash.substring(1);
$('body').className = 'bg-'+flag || ($('body').className=='bg-org'?'bg-blue':'bg-org');
}, false);
$('#switch').addEventListener('click', toggleState, false);
function toggleState(e) {
var flag = $('body').className=='bg-org'?'bg-blue':'bg-org';
// 在url中写入新的hash值
location.hash = flag.split('-')[1];
$('body').className = flag;
}
</script>
需要注意的是每次hash发生变化时都会触发onhashchange
事件。而onpopstate
事件只会在历史记录(history entry)变化时触发,比如执行浏览器的前进/后退操作。
最后
本文介绍了pushState
/ replaceState
诞生的背景以及API的使用。又通过一个简单的实例与location,hash等技术进行了对比。相信大家已经可以很直观的看到pushState
和 replaceState
的作用及区别。如有错误的地方欢迎交流指正。
随着HTML5标准的确定,pushState与ajax技术,将会在单页应用中发挥越来越重要的作用,国外也有一个叫pjax(pushState+ajax)的库将它们予以封装。
history.pushState无刷新改变url的更多相关文章
- 通过history.pushState无刷新改变url
通过history.pushState无刷新改变url 背景 在浏览器中改变地址栏url,将会触发页面资源的重新加载,这使得我们可以在不同的页面间进行跳转,得以浏览不同的内容.但随着单页应用的增多,越 ...
- 使用ajax和history.pushState无刷新改变页面URL onpopstate(转)
Javascript代码 var htmlData1 = $.ajax( { url: "/getXXXResponse", async: false }).re ...
- 使用ajax和history.pushState无刷新改变页面URL
表现 如果你使用chrome或者firefox等浏览器访问本博客.github.com.plus.google.com等网站时,细心的你会发现页面之间的点击是通过ajax异步请求的,同时页面的URL发 ...
- 使用ajax和history.pushState无刷新改变页面URL(转)
表现 如果你使用chrome或者firefox等浏览器访问本博客.github.com.plus.google.com等网站时,细心的你会发现页面之间的点击是通过ajax异步请求的,同时页面的URL发 ...
- 使用ajax和window.history.pushState无刷新改变页面内容和地址栏URL
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- 使用ajax和window.history.pushState无刷新改变页面内容和地址栏URL (转)
在访问现在很火的google plus时,细心的用户也许会发现页面之间的点击是通过ajax异步请求的,同时页面的URL发生了了改变.并且能够很好的支持浏览器的前进和后退.不禁让人想问,是什么有这么强大 ...
- HTML5之pushstate、popstate操作history,无刷新改变当前url
一.认识window.history window.history表示window对象的历史记录,是由用户主动产生,并且接受javascript脚本控制的全局对象.window对象通过history对 ...
- HTML5无刷新修改URL
HTML5新添加了两个api分别是pushState和replaceState,DOM中的window对象通过window.history方法提供了对浏览器历史记录的读取,可以在用户的访问记录中前进和 ...
- HTML5无刷新修改Url,history pushState/replaceState
一.认识window.history window.history表示window对象的历史记录,是由用户主动产生,并且接受javascript脚本控制的全局对象.window对象通过history对 ...
随机推荐
- 利用mysqltuner工具对mysql数据库进行优化
mysqltuner工具使用,本工具建议定期运行,发现目前MYSQL数据库存在的问题及修改相关的参数 工具的下载及部署 解决环境依赖,因为工具是perl脚本开发的,需要perl脚本环境 # yun i ...
- LinkedList源码分析笔记(jdk1.8)
1.特点 LinkedList的底层实现是由一个双向链表实现的,可以从两端作为头节点遍历链表. 允许元素为null 线程不安全 增删相对ArrayList快,改查相对ArrayList慢(curd都会 ...
- 使用navicat premium将数据库从Oracle迁移到SQL Server,或从Oracle迁移到MySQL
有时候我们有迁移数据库的需求,例如从Oracle迁移到SQL Server,或者从MySQL迁移到Oracle. 很多江湖好汉一时不知如何手工操作,所幸的是Navicat提供了迁移的自动化操作界面. ...
- 基于struts研究传值问题
一.新建项目 struts 1.file——>new——>Web Project——>取名struts——>finsh——>将之前项目下的jar包copy到该项目下 2. ...
- python 全栈开发,Day111(客户管理之 编辑权限(二),Django表单集合Formset,ORM之limit_choices_to,构造家族结构)
昨日内容回顾 1. 权限系统的流程? 2. 权限的表有几个? 3. 技术点 中间件 session orm - 去重 - 去空 inclusion_tag filter 有序字典 settings配置 ...
- MyEclipse中把JSP默认编码改为UTF-8
在MyEclispe中创建Jsp页面,Jsp页面的默认编码是“ISO-8859-1”,如下图所示: 在这种编码下编写中文是没有办法保存Jsp页面的,会出现如下的错误提示: 因此可以设置Jsp默认的编码 ...
- WCF客户端从服务器下载数据
1.打开VS选择控制台项目新建一个解决方案Server,然后添加两个类库Contract和Service. 2.在Contract中添加一个接口IFileDownload using System; ...
- 检测cpu、主板、内存
https://jingyan.baidu.com/article/636f38bb595cebd6b84610eb.html
- hdu 5381
题解: 还是比较水的一道题 首先可以发现每个数最多被除log次,所以有连续一段相同 然后我想的是变成矩形统计前缀和问题用主席树来维护 然后发现这题很卡空间 qwq acm依旧很多64mb的题 首先比较 ...
- poj1743
题解: 后缀数组+二分答案 首先会发现这题实质上就是求最长不重复的相同子段 首先二分答案长度,之后对每一段信息进行维护 一段信息即保证这一段的sa值都大于mid即可 然后找到这段中后缀位置最大和最小处 ...