Extending Workbox: Custom strategies and plugins
Dec 19, 2020 02:00 · 1209 words · 6 minute read
(upbeat music) - [Instructor] Hi folks, we are going to take a quick tour of some ways of extending Workbox. By the end, you’ll be writing your own strategies and plugins and hopefully sharing them with the world. But first what’s Workbox? If you’ve never heard of it before you could follow that link to the docs, and then come back to this video. At its core Workbox is a set of libraries to help with common service worker caching scenarios. And when we’ve talked about workbox in the past, the emphasis has been on common scenarios for most developers the strategies that Workbox already provides will handle your caching needs.
00:47 - Workbox includes ready to use strategies like stale-while-revalidate where a cached response is used, respond to requests immediately while the cache is also updated so that’s fresh the next time around Other common strategies like network-first falling back to the cache are available for use as well. But what if you wanted to go beyond these common scenarios? What if your use case involves more arrows? I’ve got you covered. Let’s go beyond the common caching scenarios and talk about customizing Workbox to help with all your caching needs. First let’s cover writing your own custom caching strategies. Workbox version six offers a new strategy based class that sits in front of lower level APIs like fetch and cache storage.
01:47 - You can extend the strategy based class and then implement your own logic in the underscore handle method. Let’s go back to that diagram with all the arrows. This represents a strategy that can handle multiple simultaneous requests for the same URL by de duplicating them. A copy of the response is then used to fulfill all the inflight requests, saving bandwidth that would otherwise be wasted. And here’s all the code you need to implement that custom strategy.
02:22 - Just a quick note, this code assumes that all requests for the same URL can be satisfied with the same response, which one always be the case of cookies or a session state information comes into play. I’ll link to this code later, but there are a few things I wanted to call attention to. This class extends an existing strategy network first and adds in some additional state mapping, the inflight requests to their corresponding response promises. It overrides the underscore handle method, checking to see if there’s already an inflight request for the same URL. If there is, the strategy will wait until there’s a response for that earlier request.
03:08 - But if there isn’t already an inflight request for the same URL our strategy just calls the underscore handle method on its parent class to get a response and adds to the mapping of inflight requests and cleans up after itself once the response is received. And that’s all the code you need. Here’s another example of a custom strategy. This is a twist on still while revalidate where both the network and cache are checked at the same time with a race to see, which will return to response first. Let’s take a quick walkthrough code that implements that strategy like before our class extends a base. In this case, we’re extending a generic strategy class that Workbox provides.
04:00 - This is a good starting point when you need more control over the sequence of network and cache look-ups all of our response generation logic is in the underscore handle method, which has passed two parameters, the browsers request, and then a handler parameter, which is an instance of the strategy handler class. Although it’s not required, it’s strongly recommended that you use the handler parameter to make network requests and interact with the cache like we’re doing here. Those handler methods will automatically pick up the cache name you’ve configured for the strategy, as well as invoke the plugin lifecycle callbacks that we’ll talk about in a bit, A strategy handler instance provides four handler methods. There are fetch and cacheput along with the two others we saw on the previous slide. Writing a Workbox strategy class is a great way to package up response logic in a reusable and shareable form.
05:05 - You can drop any of these strategies directly into your existing Workbox routing rules. And a properly written strategy will automatically work with all Workbox plugins as well. This applies to the standard plugins that Workbox provides like the one that handles cache expiration, but it also applies to plugins that you write yourself because another great way to extend Workbox is to write your own plugins. So what is a Workbox plugin and why would you write your own? Let’s go back to the diagram we looked at before, adding in a plugin, doesn’t fundamentally change the flow of this diagram, but it allows you to add an extra code that’ll be run at critical points in the lifetime of a request. Like when a network request fails or when a cache response is about to be returned to the page.
06:02 - Each plugin responds to one or more life cycle events, which are invoked when a strategy handler interacts with a network or cache. You’d see a list of a few of the existing life cycle events here. We’ll link to a webpage for this information later on as well. Workbox version six has a number of additional life cycle events that plugins can react to all corresponding to different stages in a strategy’s life cycle. Let’s combine a couple of those life cycle callbacks into reusable plug-in that provides a fallback whenever a strategy would otherwise generate an error response.
06:43 - This class implements two lifecycle callbacks fetchDidSuceed and handlerDidError It can be added to any strategy class. And if running that strategy does not result in a 200 OK response, I’ll use a backup response from the cache instead. My colleague, Andrea talks more about using this plugin within a trusted web activity in his Chrome Dev summit talk and you can watch for that for more details. Now that you know more about custom strategies and plugins, you might be wondering which one to write for a given use case I think a good rule of thumb is to sketch out a diagram of your desired request and response flow. If your diagram has a novel set of connections, like all these extra arrows, then that’s a sign that a custom strategy is the best solution.
07:40 - Conversely, if your diagram ends up looking mostly like a standard strategy, but with a few extra pieces of logic injected at key points, then you should probably write a custom plugin Whichever approach to customizing Workbox you go with I hope this talk has inspired you to do the following. Write your own strategies and plugins, and then release them on NPM tagged with Workbox-strategy or Workbox-plugin. Or just share them with the rest of your organization. You can learn more, including a detailed look at all the sample code and events by visiting web.dev/extending-workbox. Thanks to everyone for tuning in Now go out there and extend Workbox and share what you build. (upbeat music) .