Build a Progressive Web App In VueJs, from Zero to Hero! PART 2— The Service Worker

CacheStorage API

First of all, important to understand how caching in general works. Therefore we have a look at the CacheStorage browser API. It’s a fairly new type of caching layer which allows us to explicitly manage the caching of assets. CacheStorage is nothing like AppCache, you might remember. CacheStorage is less opinionated and much more advanced, which gives us a lot more freedom.

CacheStorage is great for our purpose, as it allows us to manage our caching needs on a very granular level. Basically, we can decide individually for each single single how and when to serve it from cache or network. Even though, we can basically come up with very individual cache strategy, there are a few common once, worth knowing.

The most common are cache only, cache falling back to network, network only, network, falling back to cache and generic fallback.

The Cache-first Strategy

Our sw-precache library comes with a cache-first strategy.

That means, when the app starts to load its static files(1), the service worker intercepts the requests. Next, the service worker tries to serve the static files from the local cache storage(2). Only if not files are available there, it connects to the network to fetch them(3) and completes the app’s request(4).

Generally speaking, cache-first is a good strategy for basic offline-first implementations. However, this strategy comes with some downsides. For example, it prevents that users always see the newest version of the app, as the service worker serves preferably a cached, probably outdated, app version. In the documentation of sw-precache they recommend compensation this by

displaying a toast/alert to your users when there’s new content available, and give them an opportunity to reload the page to pick up that new content.

In the case of our tax calculator this isn’t a big problem, otherwise one of the other caching strategies could be a better choice.

Do you want to learn more about caching strategies? Just drive this tutorial in the direction you are most interested in! Participate in the poll and learn about what you really care!

read original article here