I’m working on a JavaScript function where I force the page to reload from the server using location.reload(true). The reload itself works as expected, but I’ve noticed that any JavaScript code written after that line never runs.
function refreshPage() {
location.reload(true);
// I was hoping to run some logic here,
// but this code never executes
console.log("Page reloaded");
}
I’m curious if there’s any way to execute additional logic afterjavascript:location.reload(true) is called, or if that’s simply not possible due to how browser reloads work.
If it’s not possible directly, what are the usual alternatives for handling logic that needs to run after a page reload?
Any explanations or suggested patterns would be really helpful. Thanks!
I ran into this same issue before. The reason your console.log (or any code) after location.reload(true) never runs is that the reload immediately stops the current JavaScript execution. Think of it as the browser throwing away the current page and starting fresh, nothing after the reload line gets a chance to execute. There’s no way to continue executing code in the same session after a hard reload.
A trick I’ve used is to store any “post-reload” state in localStorage or sessionStorage before calling reload, then check it when the page loads again:
localStorage.setItem('afterReload', 'true');
location.reload(true);
Then in your page’s startup code:
window.addEventListener('load', () => {
if (localStorage.getItem('afterReload') === 'true') {
console.log('Page reloaded, now running post-reload logic');
localStorage.removeItem('afterReload');
}
});
This way, you can effectively “resume” logic after a reload. I’ve used this pattern when forcing fresh data loads but still needing to execute certain callbacks afterward.
In many cases, you might not even need location.reload(true). For example, if your goal is to refresh data or UI elements, it’s often cleaner to re-fetch content via AJAX/fetch and update the DOM. This avoids the full page reload and allows the code after the fetch to continue normally.
fetch('/data-endpoint')
.then(response => response.json())
.then(data => {
updateUI(data);
console.log('Post-refresh logic executed');
});
I personally prefer this approach for better user experience and more control over what runs after the “refresh.”