How to reload page only once in JavaScript ?

In this article, we are going to implement a JavaScript code that would allow us to reload a page only once.
The Simplest implementation:
window.location.reload()
It is the simplest inbuilt method in JavaScript that will reload the page, but the task is to refresh the page/reload the page only once.
As this JavaScript method reloads the page repeatedly & to fix this issue, we are going to use Location Hash property explained in the example.
Example 1: This example describes the Location Hash property.
- The hash property sets or returns the anchor part of the URL, including the hash/pound sign (#).
- When using this property, do not include the pound (#) sign with the hash string.
HTML
<!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> |
Output: The URL changes from http://127.0.0.1:5500/index.html to http://127.0.0.1:5500/index.html#reload
Example 2: In this example, we are going to do the same thing but without using location.hash property & without changing/adding hash(#) sign to the URL of the page.
We are going to use DOM location reload() method to achieve the same.
HTML
<!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> |
Output: Page reloads without modifying the existing URL and this all is possible because of the HTML DOM window local storage.




