Khachatryan-dev

Caching Methods (Cache API) in Service Workers

Caching Methods (Cache API) in Service Workers

Aram
Khachatryan

Caching Methods (Cache API)


Service Workers allow you to manage resource caching using the Cache API. This JavaScript interface gives us access to the browser's cache where we can store HTML, CSS, JavaScript, images, and more.


Example: Pre-caching resources in the install event


  
const CACHE_NAME = 'site-cache-v1';
const urlsToCache = [
  '/',
  '/index.html',
  '/styles.css',
  '/main.js',
  '/fallback.html',
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(urlsToCache);
    })
  );
});
  

Example: Responding to requests from cache or network in the fetch event


  
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      // If found in cache, return it
      if (response) {
        return response;
      }

      // If not in cache, fetch from network and store in cache
      return fetch(event.request).then(networkResponse => {
        return caches.open(CACHE_NAME).then(cache => {
          cache.put(event.request, networkResponse.clone());
          return networkResponse;
        });
      });
    })
  );
});
  

Caching strategies:


  • Cache-first - First tries to get from cache, if not found - from network
  • Network-first - First tries to get from network, if fails - from cache
  • Cache-only - Serves only from cache
  • Network-only - Fetches only from network
  • Stale-while-revalidate - Serves from cache while updating from network in background

Choosing the right strategy is important depending on the application type. For example, content websites might benefit from cache-first, while applications requiring fresh data might prefer network-first.




Buy me a coffee
  • 0
  • 4

Discover More Content

Comments
No data
No comments yet. Be the first to comment!
Leave a Comment
You must be logged in to leave a comment.Login