首页 > 编程 > JavaScript > 正文

使用JS判断页面是首次被加载还是刷新

2019-11-19 11:28:10
字体:
来源:转载
供稿:网友

1 利用window.name属性在页面刷新时不会重置判断(在该属性空置的情况下可使用)

if(window.name == ""){ console.log("首次被加载"); window.name = "isReload"; // 在首次进入页面时我们可以给window.name设置一个固定值 }else if(window.name == "isReload"){  console.log("页面被刷新");}

2 使用sessionStorage或cookie来判断

与window.name实现方法类似在首次加载时设置一个固定值 之后判断即可

这里以sessionStorage来为例

if(sessionStorage.getItem("isReload")){   console.log("页面被刷新");}else{ console.log("首次被加载"); sessionStorage.setItem("isReload", true)}

3 可以使用window.chrome对象 (该方法只在谷歌浏览器中可用 其他浏览器无chrome对象)

该对象提供了一个loadTimes() 方法 执行该方法我们会得到一个有关页面性能的对象
其中有一个navigationType属性可以帮助我们判断页面是加载还是刷新
它有两个值 Reload(刷新) 和 Other(首次加载)

所以我们可以通过if判断:

if(sessionStorage.getItem("isReload")){   console.log("页面被刷新");}else{ console.log("首次被加载"); sessionStorage.setItem("isReload", true)}

使用window.chrome.loadTimes方法会报警告

isreload.html:20 [Deprecation] chrome.loadTimes() is deprecated, instead use standardized API: Navigation Timing 2. https://www.chromestatus.com/features/5637885046816768.

官方已经说明该方法被弃用了 让我们使用 标准化API: Navigation Timing 2
所有上面代码需要改下:

if (window.performance.navigation.type == 1) { console.log("页面被刷新")}else{ console.log("首次被加载")}

总结

以上所述是小编给大家介绍的使用JS判断页面是首次被加载还是刷新,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表