2

My web app renders asynchronously via javascript. The issue is that the browser caches a version of the page and then doesn't update the cache when I manipulate the DOM. Then when I click the back or forward buttons, the browser loads the cached version of the webpage, which is not the final version.

My patch is to force a page reload whenever a popstate event fires.

window.addEventListener('popstate', () => window.location.reload())

But that solution slows down the page load significantly.

I am wondering if there is a way to force a browser cache update whenever I manipulate the DOM. Something like:

window.location.forceCacheUpdate()

I want to be able to update the cache without reloading the entire page.

Jeremy Gottfried
  • 1,061
  • 13
  • 28
  • https://stackoverflow.com/questions/7413234/how-to-prevent-caching-of-my-javascript-file Or http://thisinterestsme.com/stop-javascript-cached/ in both cases you have to add additional text to your script – divyanshch Feb 11 '19 at 21:07
  • 1
    The browser caches HTML, not the DOM. – Barmar Feb 11 '19 at 21:40

1 Answers1

0

You can store the updated HTML within sessionStorage then replace the static HTML request body with the locally stored HTML at load event of window or when navigation occurs, for example

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div id="div"></div>
  <script>
    onload = () => {
      console.log(sessionStorage);
      const div = document.getElementById("div");
      if (sessionStorage.getItem('html') === null) {
        div.innerHTML = '<p>1</p>';
        sessionStorage.setItem('html', encodeURIComponent(div.innerHTML));
        setTimeout(() => { console.log('navigate'); history.back() }, 2000)
      } else {
        div.innerHTML = decodeURIComponent(sessionStorage.getItem('html'));
      }
      // do stuff
    }
  </script>
</body>

</html>

You can also utilize the History interface or ServiceWorker ServiceWorker Chrome extension: Block page items before access.

See Persist variables between page loads for a range of solutions for storing data between window loads.

guest271314
  • 1
  • 15
  • 104
  • 177