How to clear cache memory using JavaScript?


Cache memory, often known as cache, is a different memory system in a computer that stores frequently used data and instructions for a short period. While loading a website, the browser we are using will automatically cache some resources, such as images, scripts, and stylesheets, to be utilized again when the page is reloaded. This can shorten the time it takes for a website to load not only that but also it helps to lower the amount of data that has to be sent over the network. But this cache memory stored by the browser also has some disadvantages. If the cached resources become out-of-date or the browser cannot reload the page because it uses the cached resources, difficulties may arise. For that, we have to clear those caches sometimes.

Users can use JavaScript to clear the browser's cache memory according to their needs. Those are described below −

  • The location.reload() method − One of the effective methods that can be used to reload the current page and disable caching. The User has to give a boolean value as a parameter, and the value should be set to true. Instead of using a cached version, this technique forces the browser to reload all resources from the server.

  • The navigator.serviceWorker.getRegistrations() method − This is another method that runs the unregister method for each registration after retrieving all service worker registrations using the navigator.serviceWorker object's getRegistrations() method. The browser will then delete its HTTP cache as a result.

  • The caches.open() and cache.delete() method − This method opens a named cache using the Cache API and then uses the delete() method to remove a specific resource from the cache

  • The localStorage.clear() and sessionStorage.clear() method − To remove all key-value pairs from the localStorage object, the user can use the localStorage.clear() method. While the sessionStorage.clear() function can remove all key-value pairs from the sessionStorage object.

Using location.reload() method

When the boolean parameter is set to true, the location.reload() method will not cache the current page and will instead reload it. If you specify true as the argument, the browser will download all resources—including pictures and scripts—from the server directly instead of using a cached copy.

Syntax

location.reload(true); 

In the above syntax, location is the global object of JavaScript, and reload the method of the location.

Example

In this example, we used the location.reload() method to clear cache memory using JavaScript. We have used the button ‘Clear cache’ and associated it with a click event. The click event handler executes the location.reload() method with the parameter true. JavaScript forces the browser to reload the webpage with no cache files whenever the user clicks the button.

<html>
<body>
   <h2>Clearing <i> cache memory </i> using JavaScript</h2>
   <div>
      <img
      id = "myImage"
      style = "height: 200px"
      src ="https://www.tutorialspoint.com/javascript/images/javascript.jpg"/>
   </div>
   <button onclick = "clearCache()">Clear cache</button>
   <div id = "root" style="padding: 10px; background: #bdf0b8"></div>
   <script>
      let root = document.getElementById('root')
      function clearCache() {
         root.innerHTML += 'Cache cleared using location.reload(true)'
         windows.location.reload(true)
      }
   </script>
</body>
</html> 

The webpage showed this message and quickly reloaded with the latest files.

Using navigator.serviceWorker.getRegistrations() method

In JavaScript, navigator.serviceWorker.getRegistrations() method is the second method the user can apply to clear cache memory by unregistering all service worker registrations, the navigator.serviceWorker.getRegistrations() method can be used to empty the HTTP cache of the browser. One type of web worker, called a service worker, is used to carry out numerous processes in the background, like caching resources. The browser must erase its HTTP cache by deactivating all service worker registrations.

Syntax

if ('serviceWorker' in navigator) {
   navigator.serviceWorker.getRegistrations()
   .then(function(registrations) {
      for(let registration of registrations) {
         registration.unregister();
      }
   });
} 

In the above syntax, we check if the ‘serviceWorker’ is available in the navigator object. Then we used the navigator.serviceWorker.getRegistrations() and registration.unregister() methods to unregister the service worker.

Example

In this example, we clear the cache memory by unregistering the service worker using JavaScript. We have used the ‘Clear cache’ button and associated it with a click event. The click event handler executes a function that unregistered the service worker. The navigator.serviceWorker.getRegistrations() and registration.unregister() methods are used to unregister the service worker. After unregistering, we showed a message on the webpage.

<html>
<body>
   <h2>Clearing <i>cache memory</i> using JavaScript</h2>
   <div>
      <img id = "myImage" style = "height: 100px" src ="https://www.tutorialspoint.com/images/logo.png" />
   </div>
   <button onclick = "clearCache()">Clear cache</button>
   <div id = "root" style = "padding: 10px; background: #b8f0ea"></div>
   <script>
      let root = document.getElementById('root')
      function clearCache() {
         root.innerHTML = 'Cache cleared using navigator.serviceWorker.getRegistrations()'
         if ('serviceWorker' in navigator) {
            navigator.serviceWorker
            .getRegistrations()
            .then(function (registrations) {
               for (let registration of registrations) {
                  registration.unregister()
               }
            })
         }
      }
   </script>
</body>
</html> 

Clearing cache is a best practice, but it may also impact the web page’s performance sometimes, as all files must be fetched again. JavaScript has the power to clear the cache that can be used as per the requirements.

Updated on: 31-Oct-2023

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements