Home >Backend Development >PHP Tutorial >js怎么判断页面是否为首次被加载?

js怎么判断页面是否为首次被加载?

PHPz
PHPzOriginal
2016-06-13 11:23:502340browse

js怎么判断页面是否为首次被加载?

js判断页面是首次被加载还是刷新

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 (window.chrome.loadTimes().navigationType == "Reload") {
  console.log("页面被刷新")
}else{
  console.log("首次被加载")
}

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

官方已经说明该方法被弃用了 让我们使用 标准化API: Navigation

所有上面代码需要改下:

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

更多相关知识,请访问 PHP中文网!!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn