JavaScript 如何只重新加载页面一次

JavaScript 如何只重新加载页面一次

在本文中,我们将实现一个JavaScript代码,使我们能够只重新加载一次页面。

最简单的实现:

window.location.reload()

这是JavaScript中最简单的内置方法,它会重新加载页面,但任务是只刷新页面/重新加载页面一次。

因为这个JavaScript方法重复地重新加载页面,并且为了解决这个问题,我们将使用 Location Hash属性 进行解释:

示例1: 这个示例描述了Location Hash属性。

  • hash属性设置或返回URL的锚部分,包括井号(#)。
  • 当使用这个属性时,不要将井号(#)和哈希字符串一起使用。
<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
  <meta charset="UTF-8" /> 
  <meta name="viewport" content= 
    "width=device-width, initial-scale=1.0" /> 
  <title>Document</title> 
</head> 
  
<body> 
  <script lang="javascript"> 
    const reloadUsingLocationHash = () => { 
      window.location.hash = "reload"; 
    } 
    window.onload = reloadUsingLocationHash(); 
  </script> 
</body> 
  
</html>

输出: URL 从 http://127.0.0.1:5500/index.html 变成了 http://127.0.0.1:5500/index.html#reload

JavaScript 如何只重新加载页面一次

示例2: 在这个示例中,我们要做同样的事情,但是不使用 location.hash 属性,也不改变/添加页面URL的哈希(#)符号。

我们将使用 DOM位置重载() 方法来实现相同的效果。

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8" /> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0" /> 
      
    <script type='text/javascript'> 
  
        // JavaScript anonymous function 
        (() => { 
            if (window.localStorage) { 
  
                // If there is no item as 'reload' 
                // in localstorage then create one & 
                // reload the page 
                if (!localStorage.getItem('reload')) { 
                    localStorage['reload'] = true; 
                    window.location.reload(); 
                } else { 
  
                    // If there exists a 'reload' item 
                    // then clear the 'reload' item in 
                    // local storage 
                    localStorage.removeItem('reload'); 
                } 
            } 
        })(); // Calling anonymous function here only 
    </script> 
</head> 
  
<body></body> 
  
</html> 

输出: 页面重新加载而不修改现有的URL,这一切都是因为HTML DOM窗口本地存储的原因。

JavaScript 如何只重新加载页面一次

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程