 Your progressive web app needs to load instantly and reliably, never showing the downer saw, even under uncertain network conditions. Let's take a look at how service workers allow you to do that. Hello, I'm Mariko. I want to start with a user scenario for a typical app. Let's say I'm sitting at a park and I'm humming to myself and suddenly thinks that's a great lift, I could totally use that in a song. So I open up my voice memo app to record myself. Unfortunately, my phone doesn't work in this park and my web-based app fails to load. Users have learned not to expect the same reliability from the web platform as they do others. Users expect it to work instantly, regardless of where they are, what they're doing or what the local connectivity is like. And unfortunately, this isn't just about no connection. Slow and intermittent connection affect users just as much. Because of the way web pages are typically constructed, a slow connection can increase the time that a page takes to load. On top of that, mobile phones sometimes are not online. Even when your phone says you have four bars, it might not have a live connection. In order to become reliable, we need instant loading and offline to be part of the web platform experience. Because remember, as we said in previous video, after three seconds, 53% of users abandon sites. Users are not willing to wait. Globally, over 60% of mobile connections use 2G. We need to do something. We need to be able to build reliable sites and apps for users when connectivity doesn't exist or when it's slow. It's clear that we need to stop relying on the network. The key to building instant loading and offline-capable web app is a relatively new technology called service walkers. In an earlier video, we talked about how a service walker is a programmable proxy sitting between the network and the browser, but it's more than that. When a page registered a service walker, it has a set of event handler to respond to things like network requests, push messages, and updates to the service walker. Because it's event-based, it doesn't have to be listed in memory unless it's handling one of those events. I'll say it again because I think it's important. It's not consuming any system resources until it's been walking up to handle one of those events. In fact, even if the browser is closed, the OS can wake up a service walker. We are no longer limited to the model where web app must be loaded in an active tab to be useful. This is important because it introduces an app-like lifecycle for websites and web apps. When a service walker is first registered, it fires an install event, which we can then use to prefetch the resources we need for our app and cache them locally. This is like install as you go. In effect, we are learning a fully scriptable install much like native app. No bulky zip files. We have file level control over what is fetched, how it's cached, and how it's updated. Once the service walker has been activated, we now have a full control over how the system serve your app's resources. We can inspect network requests, rewrite them, get a response from the network, or respond with something from the cache. We can even synthesize our own response. All of this is completely transparent to the user. In fact, well-constructed service walker can act as a very smart caching system and be transparent to the rest of your app. It is just a progressive enhancement of the network and the cache, choosing smarter ways to respond to the requests. It gives us the ability to make our app reliable even when the network isn't because we have full control over the response. Service walkers are progressive enhancement. It's important to understand that the first time you load the page, it's still going to load from the network. The initial page has already been retrieved from the network and the page resources will be loaded normally. The service walker will come into play only on the second request, though there is one caveat to that. I'll cover that in a moment. Let's dive in and take a look at lifecycle of a service walker. When the page is first loaded, it registers a service walker for a specific scope. For now, think of the scope as the set of page that service walker will handle. An install event is then fired and the code in your install handler is executed. Then the service walker goes to idle, essentially sitting there quietly. When the page is reloaded or you hit another page covered by the service walker, the service walker is activated, ready to handle all of its events. At the same time, the browser also makes an asynchronous request to the server to see if the service walker has changed since it was last retrieved. Once the service walker has handled all of the events, it goes to idle and eventually it's terminated, ready to spin up again when any new events come in. Let's keep going with our previous example and see how a service walker gets updated. Since we've already been to the page, the service walker is already installed and immediately activated. Then, just like before, the browser checks with the server to see if the service walker has changed and this time it has. The new service walker is downloaded and installed, but goes to idle and the original service walker is activated and still handling requests. In fact, our original service walker will remain active until all the clients using it has been closed or until it used skip waiting and clients.claim. We'll dive into those more in a second. This is important to remember as you are working on your own service walkers. This isn't the problem for users, but as a developer, you may find yourself with multiple service walkers installed and waiting because the original one hasn't been terminated yet. Enough theory. Let's take a look at how to implement our own service walker. The first step is registering a service walker in the web page. In our HTML page, we will place a small piece of logic. First, we check if the service walker API is available in the browser. Then, if it is, we call navigator.servicewalker.register to register the service walker with a reference to the location of the service walker JavaScript file. Next, we need to handle the install event, which is fired after the service walker JavaScript file has been downloaded and parsed. Let's start with something basic. Remember, earlier I mentioned that when a service walker is installed the first time, it doesn't take immediate control of the page. You have to wait for the page to be reloaded. Well, there is a way around that. Calling self.skipwaiting tells the service walker you wanted to skip waiting and go right to work. We'll use the install event to pre-fit the resources we need and cache them in the local cache, ensuring that the files can be loaded instantly and reliably. In effect, this install event handler is your opportunity to have a fully scriptable install process, just like native app. You have absolute control over what resources are prefetched and how they are cached. First, let's open up a cache object referenced by cache name. Then, we'll use cache.atall to retrieve the resources we've listed in file to cache and store them in a browser cache. In a little implementation, you should make sure that you take care of any exceptions here. If one of the files were to fail while downloading, the entire event fails and the service walker wouldn't be activated. And finally, once everything has been added, we want to call self.skipwaiting so that our service walker takes control immediately. There's one other thing I want to point out. We wrap that whole code block in event.waituntil. This makes sure that the service walker isn't terminated or go to idle while we're waiting for the embedded promise to complete. Once everything has been cached and our service walker has been activated, it's a good idea to clean up the cache. For example, remove any outdated resources from the cache. There are plenty of ways to do this, but in this case, we iterate over the list of keys from the cache, then delete any cache that don't match the current cache name. And there's one more thing we need to do. By calling self.clients.claim, we tell the browser that we want this service walker to take control of all the clients. That means we don't have to wait until other service walkers are terminated. We are ready to go immediately. But at this point, if you were to go flying, then you'd still get that dreaded offline dinosaur. But why? We haven't added a fetch event handler yet, which allows us to respond to the network requests that are made by our page. Let's assume that all of the required resources for our app are already in the cache. But if it's not, we'll just go out to the network to fetch it. When a network request is made from our webpage, our service walker wakes up and the fetch event gets triggered. Next, we check to see if the requested resources is in the cache. If it is, we return the version from the cache. Otherwise, we request it from the network and return that. We now have a reliable experience that loads almost instantly. Our app will work whether we are online or offline and it will load extremely quickly because we've eliminated any potential network latency. Our last step is to let the page know that the service walker is now registered and ready to go. This is helpful if you want to indicate to the user that the page is offline capable. Earlier, I mentioned the scopes. One of the cool thing about service walker is that you don't need to register it on every page you want to use it. You only need to register it once and any page within the scope will be handled by the service walker. The easiest way to define a scope is simply based on where the service walker is served from. I recommend that you serve your service walker from the server loot. That means every resource requested will be handled by the service walker. If you put it in your script directly, only resources served from there will be handled by the service walker. In this case, unless the page registering the service walker is also in script directly, it won't be handled by the service walker. Putting the service walker in your server loot gives you the first chance at responding to any network requests and helps to ensure your app is reliable and loads almost instantly. The magic a service walker provide is that you are in control. You get to decide what gets cached, how it's cached and how it should be returned to the user. I've shown you the cache first with network fallback strategy. It provides a fast, reliable experience for users. There are several different caching strategies and depending on your app scenario, you might want to use different one or even multiple strategies for different kinds of requests. Let's take a look at some of the different strategies. The cache first with network fallback strategy we laid out, it's pretty straightforward. Always go to the cache first and if the request matches the cache entry, response with that. Otherwise try to fetch the resources from the network. This option is good for resources that don't change often. It will give you a very fast response since response came out of the cache directly but it doesn't update. On the negative side, if an item is not in the cache, it is not added after it's retrieved from the network. Network first and falling back to cache means you give online users most up to date content but offline users get an older cached version. If the network request succeeds, you'll most likely want to update the cache entry. However, this method has flaws. If the user has an intermittent or slow connection, they'll have to wait for the network to fail before they get the content that is already on their device. This can take an extremely long time and it's a frustrating user experience. Cache first then network requires the page to make two requests, one to the cache and one to the network. The idea is to show the cached data first, then update the page when or if the network data arrives. Sometimes you can just replace the current data when new data arrives, things like game leaderboard. But that can be disruptive with larger piece of content. Don't make something that user may be leading or interacting with disappear. With the generic fallback strategy, a request is made first to the cache, then the network, and if both of them fail, a second request is made to the cache for a generic page. This is ideal for secondly imagery, such as avatars failed post-request and unavailable while offline page. One of my favorite use for this is a newspaper that gives you a close word puzzle to play while you're offline. And of course, there are more. Cache only, network only, service worker templating, just to name a few. But the core point here is that when it comes to caching strategies, you are in complete control over how to respond to requests. You can manage the network and the cache so that you can build a consistently reliable and performant solution. Because you have so much control over the network, it can seem quite daunting to get started and to debug experience. Luckily, there are a number of tools that can help you. The Chrome DevTools have added new set of tools to help you work with service workers. In the DevTools, you will find application tab. In application tab, you can inspect the service worker and register it, false it to update, simulate offline behavior, and more. We'll talk more about these in the tooling video. And of course, Firefox, Opera, and other browsers have similar tools for debugging service workers. DevTools let you inspect not only application strollage, like IndexedDB, but also inspect cache strollage. In the past, we used to recommend people use incognito windows when developing service workers because it made it easy to start fresh when you need to. But the new clear strollage pane simplifies things tremendously. I use this one a lot. Next, we have a tool that can speed up your service worker development. Walkbox is a collection of libraries to help you develop PWA. If you remember the code for a cache first service worker from earlier, it was a bit cumbersome to write. With Walkbox SW, this turns into simple declarations for caching strategies on multiple resources. But you are still in control of your site. It's just a set of packaged loudings and strategies. So I hope this has given you a good understanding of service workers and how they provide the core of instant and reliable experience for progressive web apps. Thank you.