简体   繁体   中英

Update browser cache with javascript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM