Implementing One-Time Page Reload with Session Storage
To reload a page only once, we can use session storage to keep track of whether the page has already been reloaded.
Example: In this example the location.reload(true) function in JavaScript forces a full page to reload when triggered, bypassing the browser cache. It ensures the latest version of the page is fetched and displayed to the user.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Force Reload on Button Click</title>
</head>
<body>
<button onclick="location.reload(true)">
Reload Page
</button>
</body>
</html>
Output:
Example 2: In this example, we use JavaScript to reload the page once by storing a flag in the browser’s local storage, ensuring it executes only once per session.
<!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.
How to reload page only once in JavaScript ?
Reloading a webpage once using JavaScript ensures that users see the most up-to-date content on their initial visit. This technique leverages session storage to track if the page has been reloaded, enhancing user experience by preventing unnecessary reloads and ensuring content freshness.
Using Location.reload(true)
The Location.reload(true)
method in JavaScript forces the current webpage to reload from the server, bypassing the cache. The true
parameter triggers a hard reload, ensuring the latest version of the page is fetched.
Syntax:
location.reload()
Contact Us