In this video, learn how to create and open a custom cache with built-in cache invalidation. Discover why that is important and how to do it.
- [Instructor] Now we are going to look at how to create cache on the front end. Browsers provide the cache API for us to do this. This API is available from both the Service Worker, and in our normal jobs. The API spec is the same, no matter where you use it from. However, it is defined as part of the Service Worker spec, and it's most effective when used from inside Service Worker. So that's what we're going to do. Let's take a look at our exercise files. Generally, it's a good idea to have different caches for different kinds of resources. To start with, we're going to look at caching static files, such as images and CSS. So we'll open a cache for each of these. First, we need to define the names of our caches. We're going to do that in a current caches constant. We will use the cache name to interact with cache later on. When defining a new cache, we should version it, we will also look at how to do this later on in the Caching Validation video. First of all, we're going to create a new constant, called CurrentCaches, which is going to contain an object. In here, going to set the key of our first cache and it's name, and then a key of our second cache with its name also. Now that we have set the names of our caches, we need to create them when the Service Worker is installed. In our install event, we're going to do event.waitUntil which tells the install to wait until this particular piece of code is finished. Now we're going to open a few caches, so we're going to do a Promise.all so that we can perform multiple actions. Inside the Promise.all, we're going to give it an array of the things we want to perform. Now, the first thing that we're going to perform, is a caches.open. This method allows us to open a new cache. It takes a string of the name of the cache. So we're going to use the currentCaches.css that we set up earlier. This returns a promise, so, we can hook into it with a .then. This will open the cache and then allow us to interact with it, from in here. Now we're going to open two caches, so we're going to repeat that process, again, calling caches.open, don't forget the coma, because remember we are inside the Promise.all array. Again, we going to use currentCaches this time using the other key, and again, this returns promise, so we can add a callback for us to interact with it.