Sessions is temporarily moving to YouTube, check out all our new videos here.

Introduction to Service Workers

Phil Nash speaking at JS Monthly London in April, 2016
Great talks, fired to your inbox 👌
No junk, no spam, just great talks. Unsubscribe any time.

About this talk

Service Workers are the biggest thing to hit the browser since XMLHttpRequest. In this talk, Phil Nash introduces us to what the Service Worker can do for your app and more importantly, your users. You’ll see the surprisingly small amount of code you need to get started with a Service Worker and finally you’ll take a look at Progressive Web Apps and how the Service Worker will take part in a revolution for web applications.


[00:00:02] Good evening. My name is Phil Nash and I’m a developer evangelist for a company called, Twilio. Twilio, if you don’t know, is a communications platform for your applications to communicate with your users via voice, video, or messaging, using the tools and languages or frameworks that you already know. I’m not really here to talk about Twilio, they might crop up in some examples later, but what I am here to talk about today is service workers. [00:00:32] I’m going to go with the quick introduction first. Service workers are very much script that intercepts network requests so web developers can treat the network as an enhancement and provide offline experiences for users of web applications. All makes sense? We can do to the pub then. Fantastic. It’s just down there. What’s it actually called? What’s the pub called? The Grand Tavern? Wonderful place. I used to drink there when I worked at a previous company. Excellent. We have a slightly longer introduction to service workers, for those of you who are still here. I want to start off with how delighted I was the first time I saw a service worker and what it does and how it works. I have no idea why anybody called it, “XMLHtttpRequest” given that it’s not necessarily XML, it doesn’t have to use HTTP, and never returns a request to you. It’s still a pretty cool thing that we’ve managed to make quite a lot out of in the interim ten or so years, I guess, that we’ve had access to it and we’ve made some amazing stuff on the web. I think this next step change is the new thing we have for that is service workers. I believe in the future we will wonder how we coped without service workers? How we ever bothered making websites without these things. [00:01:48] I want to talk a little bit about the birth of the service worker. That brief introduction at the start, the service worker provides an offline experience for users, but we have this already a few years back with the application cache. It would look something like this. You started with a cache manifest, you’d have some comments, you’d talk about caching certain URLs. You loaded this as an attribute in the HTML element of your site and boom, your site then worked offline. Fantastic. Everything was done, you could go home early or off to the pub early, if that was your preference, and everything was fine. Except, this is a really easy, declarative way of saying, “This stuff should be available offline and whenever I want it”, but it turned our when people tried to use it for real applications, they found otherwise. It was Jake Archibald of Google who has famously declared the application cache a number of things in his time, but if you search for that phrase you will get talks, articles, and all sorts of varying reasons why the application cache did not do the job it was supposed to do. I know I use the application cache one or two times perfectly reasonably but then that was a single page application that didn’t need to go anywhere or do much particularly difficult. That was where it was difficult for applications to actually use. [00:03:15] In early 2013, February 2013, the spec for the service worker was born. This is with Alex Russell’s GitHub and contributed it initially by Alex Russell and Jack Archibald, in order to build up a much better way of making sites work offline. You can use it today. It then dropped into browsers just over a year ago in Chrome 40 and Opera 27, although, I’ve been telling people 24 for a while because “Can I Use” tells me that and that’s not true as far as Opera tells me. Back in January 2015, these two browsers were released and the service worked was unleashed on to the public. Then, actually earlier this year, January this year, Firefox eventually caught up with version 44 and their pretty happy about that. They got their service worker support out as well. What does it really do? We saw that nice easy applications cache which worked nicely for getting a simply site offline. What does the service worker do? It is a harder JavaScript to API and here comes a little bit of code. First of all, you need to register a service worker. This is on your page. You can check for the existence of the service worker object on the navigator, if you’re working with browsers that aren’t these, and you register it. You point at another bit of JavaScript. You can give it a scope and a path that the service worker works underneath but the default is just to use the root and that’s easy enough for the demonstration. Then that returns a promise. Promise is another one of those nice things that come along at the right time, such that if things work then we get a response and if things don’t work we have to catch that and do something about it. In this particular case, cry about it, I think, yes. That’s what you need to do on the front end to register your first service worker. [00:05:24] Then, as I said, that service worker intercepts network requests. It actually then works on behalf of any tab, any browser tab that has that site that registered open. It works for everyone and you can listen to events, like the Fetch event. It’s basically like a proxy that you control inside the application. It’s kind of cool. Right? You might get a little worried about that because if somebody else were to load a service worker script for your page for a user and then suddenly you lose control of your entire website for that user. Terrifying, but don’t worry because you’re actually not allowed to use service workers on sites that aren’t secure. Service workers will not work over anything less than HTTPS, so this is part of a whole other push to get the web onto more secure protocols and this is certainly one of those things you cannot use without HTTPS. Interestingly enough, I think geolocation just knocked into Chrome, which now has to be done via HTTPS as well, as do camera and microphone from the “Get User Media” API. None of that can be done on an insecure site anymore. You might be wondering how you test this, but don’t worry, the local host is also known as a secure domain in this particular case. It’s okay to work when you have a server on your own laptop. [00:06:56] I want to show you how this works. This is where we see whether this microphone stand works as well. I was fiddling about with it before. It doesn’t quite fir the microphone but I’m going to try. Good. Let’s go have a look. This is a website. It works. I’m actually going to be triggering offline here by cancelling the server. If I go back it’s dead, that’s a shame. Let’s fix that. We’ll bring it back to life first and then let’s write the code for it. You can read this at all? This is the bottom of that page. It is the simple cover template for Bootstrap. I thought it looked nice enough. I’ve got a script down here which I’m going to start work with. This is where I’m going to use that service worker. This is the kind of stuff we saw just in the slides there. That’s kind of what we need to do; although, let’s get the call back, just to make sure it did work. Great. That’s how we register our service worker. Easy. This is the service worker file that I’ve got. First of all, I’m actually going to listen to a different event. There’s a few events in the lifecycle of a service worker. The first one is the install event, which gets called funnily enough when that service worker gets installed. This is the point where we can do some pre-caching and some work to set this site to work offline. I’m going to use event.waitUntil and this is a new thing for events. Basically, the service worker itself can kind of get killed by the browser at any time, because it runs in the background of the tab, but waitUntil in the context of an event will keep the service worker alive until the work that’s done in that waitUntil is complete. In here you pass a promise and once that promise resolves, the event stops waiting and the service worker can be killed again. [00:09:15] In this case, we’re actually going to open up a cache. Caches is just an API that you get from within the service worker. We’re going to open this one, which I’m going to call, “jsmonthly”. You can call that whatever you like. It’s quite useful to be able to rotate through caches. Of course, these also return promises. We can use that again and we’ll get that cache in that resolved promise. Then using that cache, we can add all our pages. All our things that we want to store offline. In there, I’m going to put index.html, that’s just the homepage. This is maybe not exactly how you do it but this is just an example. We’re going to have the index and the CSS and that’s all we should need. That’s saved them. Then, we can listen to that Fetch event. In this case, we actually want to do something about it. We’re just going to take this wholly offline now. In this case, we’re going to event.respondWith, because what we’re going to do is – the service workers come with a request and a response API, lower down primitives that talk about actual request and response. You can create a response out of nothing if you want to but it happens that we’ve put our responses in that cache right now. Again, event.respondWith either takes a promise or a response object and hopefully that promise resolves to your response subject. What we’re going to do is open up that cache again. What did we call it? “jsmonthly”. When we get that cache, we are going to just return cache.match, event.request. That’s pretty much it. What we should be able to do now is refresh this page and if we just take a look at the console we have Yay there, so the service worker did install correctly. I’ll get rid of that. I should just be able to kill the server, refresh the page, and find out that it still works. That is me refreshing the page over and over. That is now offline and that is the simplest application of a service worker. It’s pretty cool. All within 18 lines on the service worker side and that’s me making apparently a pyramid of hell that everybody hates anyway, but it doesn’t matter. [00:12:13] That’s quite simple and we can build an awful lot of this on top of there. Let’s head back over here. It worked. Cool. Why would you want to use a service worker? Why would you want to go offline? This, for a lot of people I think and I think definitely for the browser vendors who have done a lot of fighting for the web in recent years, is very much the argument for web versus native. This is particular on mobile because everybody wants a mobile app these days. Nobody wants to use a mobile website. It’s a real shame because we have the ability to make excellent experiences on the mobile web. In fact, we have a whole bunch of interesting things. We’re online by default, which means you can get that application whenever you need on the web, you just visit a URL and it’s fine, but native apps have that offline by default. They exist because they get downloaded and from the start you can open a native app and it should work. Of course, some native apps actually break that and choose that they require a network connection in order to get things done. That’s always disappointing. They have that ability to be offline by default. The web apps have that discoverability. You Google for something, you search for something, you just type in a URL and you have the application that you wanted. Whereas, native apps always have to go through that app store installation and that first usage is a difficult one, really. Especially if you’ve come from an app that you’ve logged into. Once you download the app, you now have to re-log into everything, remember that password, you’ve probably forgotten it; it’s probably a really long one, you’ll have to go through your email. I don’t know. That first native version is pretty bad. [00:14:08] Why we have service workers is very much down to the fact that this online by default thing needs to go away. We need to be able to change that to be able to build websites that are offline first. The application cache promised this but it was wrong, it couldn’t do it. The service worker promises us this and allows us to do that. We can build applications offline first that will work using the network as an enhancement for users, so they get the benefit of both an application that works straight away when you hit a URL and then works again if you’re on the tube, if you’re on a plane, if you’re somewhere without data or with spotty data, with terrible data. Jake Archibald, when he talks about this likes to talk about Li-Fi, which is the idea that you’re connected to some sort of Wi-Fi and that looks like it’s a connection but the browser and you can’t tell what’s on the other end of that. In fact, I did see a talk in which he proved that your router could be plugged into a plant and the browser, the application, they all think you’re online but at the end of that cable there’s a plant and that’s just not going to work. This is what we need it for. Even if you don’t care for offline, I think there are a lot of other benefits available from the service worker. Performance is one of them. We are actually in control of the cache, we are not fighting the browser for whatever caching it’s doing and fighting all other sites on the internet for the browser’s cache. We have control of this cache and we can keep things in it and get hold of stuff. Have a question? Go for it. [00:15:45] You mentioned the performance, does it keep a…? Asset, you can actually go and inspect the things that are in the service worker cache via dev tools. I won’t show that right now because I’m not that used to Chrome’s dev tools but they’re in there and you can find them under the service worker and workers. I’m not entirely sure exactly how it keeps it under the hood but you can go and inspect them, so it’s possible to get back at them. Then, of course, there are only other files that you as a user has seen anyway. Of course, that is sandboxed for any other applications. There is no access to that sandbox for any other web applications, anything outside of the scope that you gave that service worker in the first place. [00:16:35] Can the browser remove this box? Can the browser remove it? I mean, is it a kind of connection that the browser can remove or is it something that you control also? The idea in this case is very much that you have the control over it. Yes. It’s not just going to remove it at will. I believe there is something about the browser itself will give up 20 percent of available disk space to caches like this. There is a potential that you can come and hit the actual limit of that at some point, but you will start to get errors in the service worker when it’s trying to save stuff to the cache and at that point, this should very much be an enhancement on an existing application anyway because it’s not going to work in two browsers, so you should be able to work without the existence of this cache. It just responds with it in case. You can build stuff into this response, if you don’t match something in the cache – and I knew everything was going to match in this particular case – if you don’t match something, you can go and make a Fetch request that returns a response object and you can return that. The service worker just acts as a middle man back out to the actual network and everything is going to be fine. You can then use that to cache stuff that you’ve Fetched for the first time and get back to it again and that increases performance all round. [00:18:05] The service worker will have access to the indexdb that the site does and so you can put stuff in from the page and read it out in the service worker or the other way around. The early versions of service worker did not have a fully formed caches API; however, the polyfill then used indexdb to fill that in and yes, the things would actually be cached into indexdb but the service worker cache itself these days is not indexdb. As I say, they have access to each side of it. Indexdb because very useful if you’re doing more complicated stuff with this. You can cache all requests, yes. Any request made by your site, and that includes external requests, can be cached and can be looked after. There are some slightly difficult things with the Fetch API and cause a cross origin and stuff and if you’re not doing a cross origin thing then you if you don’t get a successful response, if you don’t get a 200 or 201 then you just get a response as a 0 and doesn’t give you any more information about what happened to it. At that point, you drop it and go to the network and hope things work out. You can, yes, intercept all network requests made by your site. [00:19:27] You can communicate between the service worker and the site using post messages. The same as you communicate with any other web worker. Similarly, there is also a lifecycle event that happens in the service worker called, “Activate” which is very good for managing your cache and taking things out of it that you’ve deemed to be over with if you’ve deployed the site and other stuff like that. Yes, you can either communicate directly with it or as part of a new service worker update flow. Cool. I will carry on because there’s a bit more to this talk. Fallbacks, fallbacks are pretty useful on top of performance because if you’re not going to go offline the whole way, then just having somebody sit and wait and watch a blank white screen while the thing loads is awful as well. Eventually, – The Guardian tried this and they’ve got a good blog post on their dev blog – that if you try and hit The Guardian, I think they’re just testing it out on the dev blog but then it works across the rest of the site if you load it up that way. If you can’t connect, if you’re not online and reading The Guardian they will offer you a crossword to do, which is kind of nice, whilst you wait to get access back again. [00:20:37] There’s more. More than just this caching and offline stuff. The service worker also gives you access to push notifications. Something that we’ve never had on the web up until now and something that native applications have definitely held over the top of us. I have a quick demo of that. One second. I’ve actually been building this myself. This is my inbox, I said I work for Twilio and this is based on a Twilio number. It just sucks down all the SMS messages sent to that Twilio number and from my number in this case. What I can do is send it a message then we should see a notification appear. That’s good, we’ll see that one later. We’ve got that but what’s kind of cool is I’m going to close that. I got some other examples here but I don’t have any other Chrome tabs open. I can send another message and I’m no longer on the website but I will still receive the push notification, which is kind of cool. We were able to do those notifications when you were on the site before but now we can do this ability to do it when you’re off the site. That works particularly well on mobile, on Android, on Chrome on Android in which you can close the browser entirely down, close all applications and a push notification will wake up the service worker, send a notification to you and wake up the browser when you hit it. That’s kind of cool. [00:22:17] Actually, that didn’t come in quite as quickly as service workers did so it arrived in Chrome 42, which was 2 versions later, and they’re still working on it as it goes through updates to how you can send data along with those messages. Firefox really sits in version 44. I do have to warn people as this point when we talk about push notifications that with great power comes great responsibility and we shouldn’t just be spamming our users with horrific notifications about everything that they don’t care about. Users need to be personable, actionable, and useful to a user or they will turn them off and you will never see that user ever again. Another cool thing is background sync. This just arrived in Chrome 49 and I have a quick demo of that as well. This is Jake Archibald’s offline Wikipedia example. If we go and hit multinational, I can just go and download it and we can corporation and it loads the thing in the background and does that. What I’m going to do is just turn off my internet, which in this case is taking out my phone. I’m not on the Wi-Fi as you can see, that’s just turned off. If I hit “legally a person” it’s going to say again, offline, but I know you wanted that so let’s load it in the background. Cool. I’ll get a notification when it’s ready. I’ve already accepted notifications from his site, so that’s another good use of notifications. Something I want to hear about. If I plug that back in, I should get back online and the browser will then go, “All right, that’s cool.” It’s registered to sync and there we go. We get the notification, we have the article and it’s going to be there straight away as well, like instant load pretty much. [00:24:06] That, I think, is an amazing use and very new use of service workers. Like I said, that’s Chrome 49, very new but very exciting and something I intend to add to that SMS based application, such that if you send a message and you’re offline, it’s going to store that and wait to send it when it comes back online. Then people always talked about Geofencing when they talked about service workers in the first place. In fact, the talk has died down, it’s just been me going, “Maybe sometime”. Possibly not, in terms of Geofencing but that would be kind of cool to wake the service worker up when you stumble into a particular radius of latitude and longitude. Maybe. [00:24:52] Then finally, this all brings us on to an exciting thing that’s being talked about a fair amount this year, which is progressive web apps. Progressive web apps are pretty much the addition of a service worker and thus being on a secure origin manifest file for a website, which allows you to talk about what the app is called, set up certain icons and splash screens and things like that for it. Such that with some user engagement, you get a downloadable web app. Something that looks very much like an app from the app store. When I talk about user engagement here, it’s not going to start asking to be downloaded as an app the first time somebody ever visits it, but if the browser deems that the person is interested in it and is coming back to this application, then it starts offering itself as a download. You get app install banners, they look pretty cool. This is an example I stole off of Addy Ozmani’s site. If you’ve come to the site a few times and that criteria are changing amongst Chrome at the moment as they try and widdle it down to something that makes sense. Eventually, you will get this banner at the bottom saying, “Hey, this can be used as an application. Do you want to add it to your home screen?” It is an improvement on the original anti-home screen from Apple and then the ways that Chrome and Android went through anti-home screen because it’s more discoverable, it’s more obvious for users. [00:26:24] Then you get that icon on the home screen. You get that same real estate that any real application uses and after a while profit. I mean, that’s why the marketing teams want you to build apps, right? Profit. We can get that just with our website – it’s fine. That ability to work offline, have all those icons and things set up and a short name set up means that Chrome, certainly at the moment, will trust your application to be good enough to live there on the home screen next to your native applications. That, I think, is kind of exciting. That’s service workers in general. If you’re not convinced by all of that right now, and I forgot to plug the audio in earlier, but if you’re not convinced by that – let’s hope this works – they are a progressive enhancement. They are something you can add to a site, something you can improve sites in more than 50 percent of used browsers right now, so Chrome, Opera, and Firefox. I think they’re cool. In the future, I think we will wonder how we coped without service workers. Secondly, in the future, we will also wonder how we coped without full on videos for browser features because I want to show you this one. Please audio, work. [Playing video 00:27:46 – 00:28:58] [00:28:59] It affects XMLHttpRequest, I’ve heard that. That is an amazing thing. That’s actually pretty much an advert for the Udacity course on offline web applications, which I advise you to take a look at if you’re interested in doing this and having a look at any more of it. It is an amazing video and yes, all new browser features are going to have to come up with better than that in order to win now, I think. That’s me, I’m excited about the application service worker. I just want to finish with one tiny little plug, if you don’t mind, in that next month, in fact, just about a month away – it’s kind of amazing – Twilio are holding a conference out in San Francisco called, “Signal” where we are talking about all sorts of communications and the future of development and communications, as well as security and other such stuff like that. I’d love if you have a look at it. It’s at and if you want to come along please use the code PNASH20 for 20 percent off tickets. One other thing, this is the first time I’ve given this talk and I really would like to know if it has helped at all. It would be awesome if you could send me a message, just answer on a scale to zero to ten, how likely it is that you would recommend this talk to a friend of colleague? If you could send a text message to that number, that would be really amazing. That would really help me out. The number is on the next slide as well. I think that’s me for right now. Thank you very much for listening to me this evening. Yes, thank you.