JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

  • The location object

window.location.href = window.location.href

Changing the current URL with a search parameter will cause browsers to pass that same parameter to the server, which in other words, forces a refresh.

(No guarantees if you use intercept with a Service Worker though.)

  const url = new URL(window.location.href);
  url.searchParams.set('reloadTime', Date.now().toString());
  window.location.href = url.toString();

If you want support older browsers:

if ('URL' in window) {
  const url = new URL(window.location.href);
  url.searchParams.set('reloadTime', Date.now().toString());
  window.location.href = url.toString();
} else {
  window.location.href = window.location.origin 
    + window.location.pathname 
    + window.location.search 
    + (window.location.search ? '&' : '?')
    + 'reloadTime='
    + Date.now().toString()
    + window.location.hash;
}

That said, forcing all your CSS and JS to refresh is a bit more laborious. You would want to do the same process of adding a searchParam for all the src attributes in <script> and href in <link>. That said it won't unload the current JS, but would work fine for CSS.

document.querySelectorAll('link').forEach((link) => link.href = addTimestamp(link.href));

I won't bother with a JS sample since it'll likely just cause problems.

You can save this hassle by adding a timestamp as a search param in your JS and CSS links when compiling the HTML.