Caching Responses from Network Fetches

This approach uses the Cache.add(url) method to fetch a resource from the network and store the response in the cache and it is also simpler and ideal for frequently accessed static assets.

Steps:

  • Open a Cache: Use caches.open(‘cacheName’) to open a named cache. This establishes a connection with a specific cache storage area.
  • Add a URL to the Cache: Use .then(cache => cache.add(url)) within the caches.open promise chain. This fetches the resource at the specified URL and stores the response in the opened cache.

Example: To demonstrate caching ‘index.html’ with Service Worker in HTML

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style></style>
</head>

<body>
    <h1 style="text-align: center;">Welcome to GFG</h1>
    <script>
        caches.open('my-static-cache')
            .then(cache => {
                cache.add('/index.html');
            })
            .catch(error => {
                console.error('Cache opening error:', error);
            });
    </script>
</body>

</html>

Output: The browser console should ideally log no errors (Cache opening error:) if the cache is opened successfully. The requested resource (/index.html in this case) will be stored in the my-static-cache for future use.

Output

How to Manage Service Worker Cache in JavaScript?

A service worker’s ability to cache resources is crucial for a performant and reliable web application. By storing frequently accessed files like HTML, JavaScript, and images, you can enable offline functionality and faster loading times.

Below are the approaches to manage service worker cache in JavaScript:

Table of Content

  • Caching Responses from Network Fetches
  • Custom Caching with Request-Response Pairs

Similar Reads

Caching Responses from Network Fetches

This approach uses the Cache.add(url) method to fetch a resource from the network and store the response in the cache and it is also simpler and ideal for frequently accessed static assets....

Custom Caching with Request-Response Pairs

This approach provides finer control by letting you specify request-response pairs for caching and offers more control for caching specific interactions or dynamic content....

Contact Us