Understanding service worker caching
Introduction
We often hear about service workers in the context of caching techniques, their importance in PWAs, and overall optimization. They enable us to create offline experiences within websites or applications, perform background sync activities, and create push notifications, among other features.

Understanding Service Worker Caching
Let us understand what service worker is and how to implement it in websites or applications.
What is a Service Worker?
According to the official definition, Service Worker is as a proxy server that sits between browser and the network layer. It intercepts network requests, can take action based on network availability, updating assets according to the requirement.
A service worker is basically a JavaScript code that runs on a separate thread in the background, without disturbing the main thread. It captures network requests, can do some operation, and provide caching and offline functionality. It acts as a middleman between the browser and the server.
Key features
- To prevent man-in-the-middle attacks, Service workers run only on HTTPS protocol and not HTTP.
- They are event-driven workers, based on an event-based architecture.
- A service worker does not have access to the DOM or Web APIs.
- It is registered against a specific origin and path.
- Not every browser supports service workers, so compatibility must be checked.
How Does Service Worker Caching Work?
- The service worker intercepts requests made by the page.
- It checks the cache for the requested asset.
- If the asset is available, it is served to the page from the cache, without making a network call.
- If the asset is not available, a network call is made to fetch it.
- Once the asset is fetched, it is saved in the cache and served to the page.

Service Worker Workflow
How to implement a Service Worker?
To start with, we are fetching three resources from the network: a script file, css file, and an image file. These resources will be cached as a backup and can be used when there is a network failure or API response errors.
At the time of registering the service worker, several events are triggered in a sequence. The first event is “install”, followed by “activate” and other events like fetch. These are used to implement caching .
Step 1: Register the sw.js file
First, create a one file for service worker logic. We will name this sw.js. Now, from script.js file, we will register the sw.js fle. In the sw.js file, we will listen to the key events to implement caching. We need to check whether service workers are supported in the browser. If supported, we register the sw.js file from our script.js file.

Register Service Worker

Service Worker Registered
Step 2: Include the files path to cache with a unique cache name
A unique name is given to the cache and the list of URLs we want to cache are added to the cache. During the install event, a new cache with unique name is opened and all the required URLs are added one by one.

Install Service Worker
Step 3: Listen to the Fetch event
We add an event listener for the fetch event to listen to all network calls. There are two common approaches to handling the fetch event:
- Network First, Cache Fallback: When a resource is requested, it is initially fetch from the network. After the resource is fetched, the cache is updated with the new resource, and the information is served to the page. The cache acts as a backup if the network fails during the request or there are some API response error from the back end.
- Cache First, Network Fallback: In this approach, we first check if the cache has the resource for the request. If found, we respond using the cached version. If not, we make a network call and respond with the fetched resource.

Fetch Network Request
Step 4: Clean up old caches
In cache memory, it’s possible to store several versions of cached information. Clearing outdated caches that are unnecessary is essential. This cleanup usually occurs during the activate event.

Activate Service Worker
Network requests before Service Worker

Network Request before Service Worker
Network requests after Service Worker

Network Request after Service Worker
Cache stored in Cache Storage

Cache stored in Cache Storage
Conclusion
Service worker is a great feature to improve web performance and providing superior offline user experiences. By using service worker caching correctly, we can optimize the load time and make our applications more fast and responsive.