Hire a Service Worker for Your Website (iii)

Image for post
Image for post
Photo by Eternal Seconds on Unsplash

In the last blog, we talk about how to register and activate a Worker. In this post, we will discuss how to implement a cache strategy, and as there are so many of them. We will be looking at the basic Network and Cache.

"use strict";
const version = 11;
var isOnline = true;
var isLoggedIn = false;
var cacheName = `ramblings-${version}`;

You can see we are using afetch() method. It starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request. The promise does not reject on HTTP errors — it only rejects on network errors. You must use then handlers to check for HTTP errors.

Here we return the default network request with return fetch(event.request), which returns a promise. We can use respondWith() to answer ASAP.

When this promise is resolved, we respond by running a function that grabs our cache using caches.open(cacheName); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.

Cloning the response is necessary because request and response streams can only be read once. In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache. They are each read once.

Now we have cached the asset, but we normally want to clean the old cache in the activation stage.

self.addEventListener("activate", onActivate);

Here we have a handleActivation Promises passed into waitUntil() in activate () that will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first fetch event on the new service worker.

In the deletion process, we first get all the cache names by calling the .keys() and then test them against our url pattern to see if it’s our cache (there can be cache created by other sources). Then we get all the cache versions that match the cache name pattern. Finally we will iterate through them and delete them.

That’s so much of it.

Happy Reading!

🔧 🔨 ⚒ 🛠 ⛏ 🔩 ⚙🔧 🔨 ⚒ 🛠 ⛏ 🔩 ⚙🔧 🔨 ⚒⛏🔩 ⚙🔧 🔨 ⚒ 🛠 ⛏ 🔩 ⚙🔧 🔨 ⚒ 🛠 ⛏ 🔩 ⚙🔧

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store