当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 使用JS判断页面是首次被加载还是刷新

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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. .

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

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

总结

以上所述是小编给大家介绍的使用js判断页面是首次被加载还是刷新,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网