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.