小样的个人空间

解决页面返回或前进时部分内容无法刷新的问题

做过H5前端开发的都知道,当页面从A跳转到B之后,此时按下浏览器的返回按钮,页面将返回到A,假如A页面的数据是通过ajax加载的,那么此时返回到A页面时页面将是空白的,即数据不会重新加载。

以下我将提供一种方法,可以在浏览器后退或前进到历史页面时重新加载ajax数据。

把这段代码封装成通用的js引入到所有的H5页面,在需要实现ajax重新加载的页面,通过设置commonReload = true;即可以触发这个操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var commonReload = false;
$(document).ready(function() {
if (!!(window.history && history.pushState)){
var hisNum = localStorage.getItem("historyNum");
//保存最新的历史记录数量
localStorage.setItem("historyNum", history.length);
//本地存储的历史记录数量跟当前数量相同时表示刷新或前进、后退等操作
if(history.length > 0 && hisNum == history.length){
var params = new URLSearchParams(location.search.slice(1));//URL参数
//historyR:本地存储的key,把URL中的参数r保存在本地用于对比
var hisR = localStorage.getItem("historyR");
//当前URL的r参数,与本地存储的参数作对比
var curR = params.get("r");
//生成新的r
var r = new Date().getTime();
//保存新的r参数进本地
localStorage.setItem("historyR", r);
//当本地存储的r参数与URL中的r参数不同时刷新页面或作其他处理
if(commonReload && (hisR == null || hisR != curR)){
//保存新的r参数进本地
localStorage.setItem("historyR", new Date().getTime());
//替换URL中的r参数
params.set("r", r);
//最简单的处理,直接刷新页面重新加载数据
window.location.href = window.location.href.split("?")[0] + "?" + params;
}
}
} else {
console.log("不支持History API");
}
});

原文:https://blog.csdn.net/immrma/article/details/79427656