Skip to content

Latest commit

 

History

History
33 lines (25 loc) · 2.12 KB

20191112.md

File metadata and controls

33 lines (25 loc) · 2.12 KB

Service woekers.

In the past week I have copy and pasted built two service workers in projects I am kinda reaching a point at which I am fairly confident about how they work.

But they are pretty woeful as you often need to jump into the dev tools to make sure they actually work/ disable them if you want to do performance checking/ debug.

In building one for runpkg.com to cache a number of our requests to unpkg.com I was so caught up in cacheing strategies that I forgot an important basic part of package management.

I went with a Stale while revalidate strategy i.e. we fetch data from the cache, and then refetch the new data and push the new data to the cache. Which would make sense in that we would always have mostly up to date data. However this was ultimately over-engineered due to a concept semver.

When making requests to unpkg.com we are fetching something like the following: https://unpkg.com/lodash-es@4.17.15/divide.js. This breaks up into a unpkg domain, the package, version and file. If we think about it the semver means that we have an immutable reference to that file, and as such it will never change. As such if we put it into the cache now, it should be the same in a year as it is today... this means that whilst objectively the better solution in most cases Stale while revalidate is unnecessary.

The solution is for the service worker to check the cache for the requests, if it is present then return it, otherwise fetch it!

event.respondWith(
    caches.open(cacheName).then(cache => {
        return cache.match(event.request).then(response => {
            // if not in cache then fetch it and add to cache
            if (!response) {
                return fetch(event.request).then(networkResponse => {
                    cache.put(event.request, networkResponse.clone());
                    return networkResponse;
                });
            }
            // if in cache then return it
            return response;
        });
    })
);

The main takeaway from this is to Keep It Simple Silly (KISS).