Check out a free preview of the full Progressive Web Applications and Offline course:
The "Service Worker Features" Lesson is part of the full, Progressive Web Applications and Offline course featured in this preview video. Here's what you'd learn in this lesson:

Steve illustrates the features of Service Workers, which can run in the background, allow for checking network availability, updating assets, access to push notifications, and more.

Get Unlimited Access Now

Transcript from the "Service Worker Features" Lesson

[00:00:00]
>> Steve Kinney: So I've definitely played the role of hype man for service worker for the last few minutes. So let's talk about what a service worker actually is. So like web worker and shared worker, service worker runs in its own thread separate from the main thread that's doing all the rendering.

[00:00:18] Here's where it becomes interesting, service worker can intercept network requests. Again think about it, we've been talking about off line. A thing sitting separate from your application that can intercept all your network request that you can program like you would one of those web workers earlier. Right, seems like we can write logic right, rather than, here's a manifest, I hope the browser did the thing I think it was gonna do, right?

[00:00:43] We can use things like conditionals and functions to actually determine these things. So, the request is gonna, like if you were to turn the WiFi off on your computer right now and send a request, the browser would still send it into oblivion. But it would send right, and if you had a service worker, you're still sitting at the gates before it gets out, right.

[00:01:10] It means your service worker theoritically catch that and say like, doesn't look like we're online, or let me try and I'll let you know how it goes, right. Using, I don't know, some kind of asynchronous construct, where you give an eventual value and you tell whether or not it works out or not.

[00:01:27] And what's even more incredible is, somebody asked earlier, if you have a web worker and you kill it, does it die? Well, if you kill it, it dies, if you kill the actual tab around it, does it die? Well, eventually all things come to an end. What's interesting about a service worker, is that it exists independent of any of your tabs.

[00:01:48] Which means you can open up like six of these front end grocers, right? And once we have service organized so you could close all of them, guess what's still running? You haven't gotten rid of the service worker, right, so it runs even when your app isn't open. Right, and when I say the word app, you're like yeah, my Twitter app does it all the time.

[00:02:07] My RSS reader syncs stuff, right, but your web applications don't do that, right? And so this kinda brings it up to this level of parity with native applications. Except that you don't have to download a 300 megabyte bundle every two weeks cuz there's a new update. You get all the advances of go to webpage, have app, right?

[00:02:26] There's this great talk at Google where they actually measured every step you had to take between you and the app like you and downloading the app, you are less likely to download it, right? It's like every time I go to a restaurant web page and they're like, download our app to see the menu I don't want to do that.

[00:02:44] We get all the advances of the web of go and see it, and I can run in the background and sync stuff for you, and work when you're offline, and stuff like that.
>> Steve Kinney: Cool, so service worker, it's a programmable network proxy, that's the fancy way of saying the hyperbolic stuff I said earlier.

[00:03:04] It's a JavaScript worker, it only works over secure domains, right, and this is why when earlier today when you’re doing this whole HTTPS dance and you’re like, I hate certificates with like a burning rage. We’re like totally got to do it, totally got to do it, it’s not cause we’re like that security I mean Mike is.

[00:03:23] But, [LAUGH] generally speaking it's because they only work on HTTPS. Because, think about this you have the ability to run in the background, right, you have the ability to intercept network requests. You know it be great if somebody else didn't hijack that ability right, so we need to encrypt all the traffic so we don't get man in the middled, and people can has all the access.

[00:03:43] So, service worker only works over HTTPS, which is why we had to go through that song and dance in the beginning. It has a predictable life cycle that we'll discuss in a second, and it is necessary for what we're gonna call the modern offline web. So now it's just be like, yeah, here's that page that I just happened to have, but to have an offline, not just web page but an offline web application.

[00:04:06] So in a normal world, things work like this, you have browser, you make network requests, things work out great, or they don't, right? As most things in life, with a service worker, it gets in the middle. It says, you wanna make a network request application, you talk to me first, and I will figure out what we do about this, right?

[00:04:23] And it could pass it on to the network, it could programmatically work with the cache. It could do all sorts of things that it can try to figure out. It could be like, let me do a few things, and I'll get back to you on what worked out best, but it sits in the middle.

[00:04:38] All right, so this is good, I've done a good job of service worker-like salesman. Here's the, I'll start with enthusiasm, so I don't get super excited about all the grain, this is enthusiasm. It is currently implemented in Chrome and Firefox, Opera and Samsung Internet happen to share a render engine with Chrome, so guess what?

[00:05:04] It's there, too, it is forthcoming in Edge, and the fine folks on the Safari team have definitely mentioned it in their five-year plan.
>> [LAUGH]
>> Steve Kinney: The nice part about service worker, again that's like to remind you like incase you got lost this is the workshop on Progressive Web Application.

[00:05:25] What's the first word? Progressive right, where have we heard that before?
>> Speaker 2: Politics.
>> Steve Kinney: Politics, where have we heard that in terms of the Web?
>> Speaker 3: Progressive enhancement.
>> Steve Kinney: Progressive enhancement, progressive enhancment is the idea that like new thing out on the web, use it, right, except like, IE6.

[00:05:48] And like, the idea that like the site should still work if you don't have the new hotness, but if you do have the new hotness, it should work even better, all right. So a big part of progressive web apps is like, they still work even if you like, I mean you don't reap the benefits but you can still have an application that can be better if they support it, right?

[00:06:08] We do a little bit of feature detection, right? So one thing I'm gonna do if you look at that first if statement, if there is a service worker property on the navigator object, right? Like in JavaScript if you say, if you have a new object and it has keys A and B and you say, object.c, you get back undefined.

[00:06:27] Undefined, happens to be falsy, right, this will actually return false in this case. So if they don't have service worker, don't run any of this code, you've now supported Safari, right. That is the end of your interaction if we're in Safari, cuz Safari is like, yeah I don't support service worker, and moving on, right.

[00:06:47] But for those enlightened browsers that do support serviceWorker, now we say, okay, so I'm gonna call navigator.serviceWorker cuz you told me you have it. And then we register a serviceWorker, right, and it's service-worker.js. We've done some fanciness with webpack today, although like Import, and you have seven exclamation points, and you name the file the same thing over again, right?

[00:07:13] So the web pack builds the correct file for you, but if you were just, crack open a folder, but in app.js and a serviceworker.js, right, you could just say service worker. I wish that we all lived in a world where we didn't need all these build tools all the time, but we do.

[00:07:29] But if you just making a very simple thing right the goal of this course is how you build like real production level app, so some of the tools are involved. But if you want to get started and actually see some simple examples later where we just we just have some files in a folder, right so you will see both of those.

[00:07:48] We'll say hey register, and like most promise like events it will either work or it won't work. And if it does work we'll have the registration of the service worker, and if not we will have something that went wrong.
>> Steve Kinney: There's a bunch of ways to see the service workers on your system this is the old way, you can go to Chrome://serviceworker-internals, and you can see all of the service workers that are running.

[00:08:14] Newer versions of Chrome actually ship with this application tab that Mike mentioned earlier, with the service workers tab on my column there. And with that, you can actually see all of the service workers for a given page. And there's a little show all in that top column where you can see the update and reload check mark checked.

[00:08:37] That will show all the service workers installed on your system. Later, when you go home, you can hit that button and be horrified by the number of web applications that are running even when you don't have any tabs open. And you can go sit there and do the cathartic exercise of unregistering all of them because you're It's slightly uncomfortable when you see that many of them.

[00:08:59] That's the thing, [LAUGH] totally, what's that?
>> Speaker 3: It's happening right now.
>> Steve Kinney: Yeah shouldn't have mentioned that until the end. Cool so they have a lifecycle, and it's not a different lifecycle than when you download an app from the app store. It's installing, then it's installed, and then you happily click on it cuz you wanna play whatever that new snake clone is, and there you go, and then it's active.

[00:09:22] And once the Service Worker is active as we just saw, it stays active, right? And it sits there, and basically until another Service Worker comes to replace it, it will remain installed in your browser.
>> Steve Kinney: So why have a lifecycle? We didn't have lifecycle with web workers, right?

[00:09:41] One, it's to make offline-first something that's possible, right? We need to actually install it so that when we leave, it stays around until someone unregisters all of them. And there's a difference between getting yourself ready. We're gonna see, Mike alluded to index DB, a database or caches. A new service worker might have different things it needs to prepare for itself.

[00:10:05] And you might wanna do that separately, and you don't wanna mess with the active one. The active one is currently intercepting stuff, you don't want the new one messing with. So there's this idea of hey, I'm preparing to take over, you're currently running, I'm not gonna get in your way.

[00:10:19] And that's seems so we only have one active service worker. You can imagine, if two tabs are running two different service workers, there's no rules anymore, right? It's the same, when Chrome has an update for you, it basically says, hey, quit all instances of Chrome, and you can have the new version.

[00:10:35] That is true for a service worker, and we'll see that in a little bit. So this is kind of more granular, we are installing, and there is an install event that we can listen for. So when it's like, I'm getting ready to install, we can listen for that install event, do some stuff, then it's installed but not running.

[00:10:52] Then it's like, okay, if there is no other service workers ready to take over. But if there is like, hey, anything that I need to do before I like, as I'm taking the stage now, anything I need to do? And then it's active and it stays active until it is pushed out, until it is dethroned by another service worker.

[00:11:10] Self which we saw in the web workers, you can add event listeners and these will allow you to for the first two of those red, salmony, red color boxes on the previous slide. Those will let you interject at the installation process and the activation process. I'm not gonna talk about that third one, I'm gonna let you look at it, internalize it, think about it and we'll deal with it in a little bit.

[00:11:33] But looks like we can listen for all sorts off fresh events that's cool. One of the trickier things, they can be a little bit maddening when you're first getting comfortable with service worker is. When you don't fully have your head wrapped around the life cycle things that you think should work, don't work the way you think they should.

[00:11:52] And there's nothing more frustrating in programming than I believe it should be this way and it's not. Like there's a reason I got into programming, so I could write some code and have my will be done. So let's take a look about that, so imagine this, you have a service worker running now it's like V2, right?

[00:12:12] And you make it, you save it, you refresh the page nothing changes, it's still your old service worker, right? Your new service workers can only take over after all of the tabs and pages running that service worker have relinquished it, right? If nobody is accessing anymore, then the new one can step in, right, and this kinda makes sense.

[00:12:39] It's like I said, when Chrome autoupdates, where this can get a little confusing is in the process of reloading a web page. First of all, there will be the situation at one point when you, if you're like me and you have 75 tabs open across three windows. There will be one of them holding onto your service worker, that will happen at one point to you.

[00:13:00] Shoot me a DM when it happens, I'll send you an emoji, but the more common one is the case where we reload a page. We're like I got one page, I hit reload, what's the issue here? So our new service worker shows up on the scene, and we're like, I reload the page.

[00:13:14] What actually happens when you reload a page, is that the browser starts up a second version of the page, connects it to the service worker, and then gets rid of the old one. But that meant that during that process, there were two connected, there was never zero connected.

[00:13:31] So what happened to your brand new shiny service worker? Still waiting in the wings cuz this is like, when is my time? People keep talking to the wall, the guy in the stage right now won't stop talking, let me get back up there.
>> Steve Kinney: And so at that point, it doesn't work.

[00:13:47] If however, all of them disconnect, so we get our new service worker, the other one goes away.
>> Steve Kinney: And then connects, then we get the fresh one, all right? So, this can be a little bit problematic and you're like, hey, I'm working on web applications. I'm reloading this page a lot, that's what I do for a living, I change the code, I reload the page.

[00:14:13] That's what I do, I'm good at it, we actually see that there are some options here. Here is the active one, you actually see when there's another one running, and you see that there is one waiting in the wings. All right, and you have some that you can hit unregister and you can go ahead and kick that one out manually.

[00:14:34] There's also some more programmatic ways to do it. On the installation event, if you say, skipWaiting, do you know what the service worker's gonna do? It's gonna push out the current one.
>> Steve Kinney: You probably shouldn't do that I think in a slide or two I'm gonna say that we regret showing you that.

[00:14:53] But in the sake of completeness, you a can oust a service worker. If you say hey, that's not a thing that I wanna do in general, but I only wanna one of them working on the app, right? You do have these tools that update on reload. Check that one right there and then every time you reload the page, you will oust the current service worker.

[00:15:15] Also, Shift+Cmd+R, Shift+Ctrl+R I believe will do the same thing. But if you just check that box in your development, hit Cmd + R.
>> Speaker 3: That'll do a slightly different thing. That'll be a cache free brand new request, and so you'll be in the first page view situation there where the service worker is ousted.

[00:15:39] The new one is waiting until everything disconnects. So you could do that, and then another refresh to allow the service worker to activate.
>> Steve Kinney: I don't want that, that's why [CROSSTALK] box.
>> Speaker 3: Yeah, exactly, check the box.
>> Steve Kinney: Cool.