Jake Archibald: The ServiceWorker is coming, look busy

Slides Transcript
Jake Archibald

Look at the apps on your homescreen. Why are they native? Why aren’t they just on the web? Its usually some combination of push messaging, background sync, offline & performance.

When native has something the web doesn’t, we should consider it a bug. Let’s have a look at the fixes, focusing on the ServiceWorker.

Video Video Video

Transcript

> Jake Archibald: Can you all hear me? Right, so, I'm not getting a whole lot of anything on the screen. (Hey ... oh, no ... here we go. And I think we are good to go. Right. We go on the screen, brilliant, hello, we've come a long way haven't we in the past 20 years since the '90s, I mean, back then you would have some friends over, it'd be going great, then two of your friends would start having a disagreement involving the release gait of ghost busters, but then it starts to get heated, none of them are backing down, the mood of the dinner party is at stake, but it's okay, for you hold aloft the answer, for you are the proud owner of Microsoft Cinemania. Giving you instant access to the history of cinema. Well, it's not really instant, first you must go to the room with the computer in and turn it on, and then the fan starts whirring, you get that friendly static crackle as the CRT monitor whirs into action, windows 3.1 slowly boots up. Then you get your desktop, eventually. And it does this (Horn sound) and that really sets expectations we are dealing with an operating system that thinks that booting successfully is a fanfare worthy moment (Applause) and by the power of multimedia C ROM you veal that ghost busters was release in the 1984, you did that in under ten minutes, the dinner party is saved. The web changed everything, with the web you get information instantly, no installation, they looked out of date the CDs almost instantly, having separate apps for these things became weird, the stuff ton internet was better, built with new interconnected with the modern world in run, the browser Runtime replaced more my native App, office tooling, code editors, native apps became the exception, if you look at the top ten selling laptops on Amazon they include chrome books that's how secondary native apps are, though that's not true on mobile. The native apps still rule, because they build to the strength of the platform and a lot of the web predates that, some of the web is hostile to mobile. This is a creative agency that I won't name; this is what you get if you visit their site. > Choosing your creative agency isn't like buying a pair of shoes, so why group make yourself Coffee and visit our site on real screen. They're kind over right, I never had a shoe tell me to Fuck off and come back when I have real feet. You can see the things they're expert in, which includes, responsive sites, of course (Laughing) the more worrying case the sites are simply hostile to just the mobile web, not just the mobile platform, this is a horrible situation, the user has gone to these sites in a browser following a deep link rather than sending them the thing they want, we send them to another thing where they can download a thing to install a thing that can run that Macon train the thing they originally wanted somewhere in in the interface. It's not a good United Nations experience, it's one developers think is good to get you after the web to the native app. Think about the native apps you use and rely on, this that is where the web is failing what caused that failure, what features do they have that can make it impossible to replicate on the web. I use these apps often, or they can't be done on the web because of push notification, that is vital for the apps in yellow, they tell me someone sent me something, or something happens in the background when the App isn't open,I rarely use trip it, I forget I have it. Then it'll send me a notification that a flight is delayed or canceled. Background Sync, from downloading pod cast to sending an e‑mail late their failed to send at the time, which sends to off line, I depend on this for more apps that I realize for playing music, checking where my hotel is, looking up a meeting location, I continue want to depend on connectivity for these things, we need better performance and integration to the O several, battery staps, accounting information, the web can't do these, and that's a bug, what gives me hope is that these are bugs that are getting fixed not just being thought about, code is landing to fix these things, and these are the ones I want to talk about today these require something new, background Sync, that happen in the background, push notification are received and dealt with in the background. Off line, doesn't run in the background but requires context to run before pages, and that thing is the service worker. And this is the Spec. That bit got a round applause at GoogleIO (Applause) don't patronize, me, I could of dressed it up a bit. I like what graphic cards into in this present, they're just circuit boards, but they need to sort of dress themselves up to make them look like the must have for people. Even though they don't do anything on their own. The boxes they come in are amazing in this kind of sub deviant arts craft, you get the usual sort of sexist nonsense you get with gaming, you always get things like the hideous off string of Sh reck and Yoda and also teenage mutant Ninja dog. So in this vain, I present to you the service worker! (Applause) that's Memrod using his evil pow tore control browser feature. We need a logo, stop me. This is something being worked on between Google Mozilla Sam sung. It has no Dom access, unlike a shared worker it can exist without a reference to it and shuts down when not in used this is the gabbinge background context we need. It's in Bruce tore day, you'll need COMCanary, you'll need go about about flags and enable experimental browser feature and restart. If chrome isn't your thing you can use fire fox nightly, go to about Config and enable service worker and give the Bruce ear restart. I'm going to stick with canary, Google played for my flight and hoe it will, it would be rude not to. And the debugging tool is forever ahead. If you want to know what support or sub features, it's service worker ready and tells you which browser support what. It's the foundation for the others, off line suffers from the same misconceptions as progressive enhancement, I think, people say my App doesn't need to work off line because my users have permanent internet connectivity, but it's not just about zero connectivity, it's about treating the network as an enhancement, when user clicks a link to your site, the URL start a navigation, a document is created, but we have to go to network to get the data for that, that can take a long time, it will come back eventually, we can't rend E. we have to send request for the Java, the images, as these come back we can start to render, but the sub resource trigger other sub resources, fonts, images used in the CSS, when they come back we get towards our find render. As a practical example I'll take train ‑‑ it's a responsive site, I was on a train when I started building it I had a moment of zero inspiration. But let's load it on a phone that's 250‑kilo births fifteen‑year‑old me would have kill you for a 256 kill birth con next, not the best today but far from the worst. So, three, two, one, go. We get the first render, that wasn't JavaScript dependent . we get content after 5 seconds that's from Flickr, those images are 200 K each, that's what it gave me if I wanted to coverer this density. First image through, after thirty‑seconds, other images start loading, after what seems like years, we get the full render. Now, that video wasn't real‑time, I had to cut it down, it took so long, those are the correct figures, we can compress the images better, we can do things to insure the top images load first,I just took what Flickr gave me. We are still beating native, the equivalent is the visit the App store, download, it's a slow user experience, but native kicks our ass on the second visit it used that initial download and install cash loads of stuff, we have the browser cash, but the whole internet is fighting for that, if we change one line in CSS or java script, we change the file name, we break the cash,we like to deploy often, we're breaking the cash office. This page register for a service worker allowing us to do something about the second load. Registration estruation is simple, miter JavaScript like, this you can also scope it to an area of your origin, and that's use informal you have single origin with many apps, like Google does with calendar and stuff like that. The default scope is the whole origin, which we'll use here, it returns a promise so you can find out if it works or not. You can register for a service worker on 750 DPS, the service worker is so power it would p a disaster it fall boss a man in the middle is a good place to butt demo stuff and local host is exempt for development. Console log, listen for install events, service worker for the first time, so let's see that in action. First, I'm going to go to service worker internal, which is where our debugging stuff is living at the moment, as you can see there's nothing there. Then I'll open the train site, a dead version of it . As you can see on the bottom corner there, our service worker is successfully registered F we go to service worker internals there, it is, there's our console log, we can launch Dev tools, we can also set break points run stuff on the console, etc… If we fast forward time a bit, the service worker terminates, that's not a bug, it's just not needed at the moment, closes to conserve memory. And congratulations, at that point, you're now wielding the power of the service worker, but what did that actually get us? Nothing. (Laughing) but, wait, oh, my God, it's actually a good thing that it does nothing. The unapologetically made it good. Compare it to App cash, if you give manifest, and that manifest only contains the words cash manifest,I would expect to go from this to this said no one ever in the world. So, we didn't want to do that, service worker doesn't do anything unless you tell it to do something, App Cache broke a lot of eggs and failed to make a omelet, has the right ingredients, routing fetching cashing, updates and version control,blouse first reverse the piles of implicit behavior, which are, of course, guarded by the army of robot wasps. If you've used that Cache before you'll know what I mean. We sort it out, without getting stung. This is the extensible web. Don't ask don't take fish, ask for a fisher rod, but take the fish as well. We need both high and low level AIs, the service worker is event driven we've seen install, it's also fetch, this fires for any navigation for your scope, but also for any sub resource from that page. In service worker internals, we're going to start off the service worker, inspect it, navigate to our train site, you see as soon as we navigate we hit the break point many if net fetch, we get one for the CSS, we skip from there, we'll get the logo, the JavaScript, we rendered before JavaScript because we care about performance, get API call to Flikr. And then get all the image requests coming in. But, hey, the cool bit is, this is ‑‑ this is an event, like other vents like clique, touch start, key down, you can present the default and do something else Y. can respond with something else. Responses can be created manually, give it some texts, and if do we, that the page gives us this to this. But the swears interesting thing here S. we delivered that without going to the network at all, making it the first off line demo of the talk only almost halfway through, but we can do better than that. When the browser discover the service worker for first time, we'll send it to the network, get it to make load of requests and get responses it might with fast it might be slow,the network is not predictable, we're not disrupting the user they already have the page open. If our response comes back we'll put them in the Cache, this pre‑Cache method is what native would do with an initial install back age, we do it in the background without disrupting the user, the loot page template, JavaScript, all the stat tick stuff, when we get a request for one of those things, we'll just get it from the Cache, the uncertainty of the network is no learn our problem, this is simple thanks to the cashing API, full control of the Cache in the install event from earlier, we get this vent ‑‑ and we can pass a promise into there that extends the installation process, use to indicate success and failure as well. Here we're going to create a Cache, give a name, and then add stuff to it, our static has sets, if any of these fail, the whole operation fails. And, service worker won't control pages, so if the install succeeds we know we have these thing in the Cach oh, there are deopinion Dennis, it's not thee canary yet, there's a poly fill, the proper implementation in a few weeks. How do we use these Cache items, responds with Cac hade.match, it will find a response that matches that request, it's done by method, URL, similar to the browser Cach e if there's no match you'll get no back, if we get no, we can send something else, what should we do instead, we could send a fall back entry, what if we want to try the network, to do this we need the make a request using JavaScript. In 1999, Microsoft engineers were design ago new excitingAPI, what should they call it, it contained abbreviations, initialisms, they shouldn't decide if it should be all caps or just the first letter like getElement by ‑‑ so they did both XMLHttpReques the ‑‑ restricted to HTTP but it isn't, and request, you get a request object back, yet you don't. We tried to modernize it is a bit, fetching some JSON, is verboten, we've been patching this API for fifteen years, I do not want to use this AI when it's old enough to drink. Thankfully, the fetch back by Mozilla, it gives lower level control, weave already seen some of it. Lower APSI usually easier to use than higher level one, HHR is so bad, it's not true here, the equivalent to this in Fetch Fetch URL gives you a promise, pass it how you want, gives you a promise, done. This is a forward thinking API, arrow functions make it easier, Async functions can make it a one liner if you want. To answer the question, how do we send this request to network, fetch. So what improvements does this give us, 3, 2, 1, go. We reverend almost instantly, we get content after a couple of seconds, we still go to the network, but our JavaScript rivered so much quicker, we're able to start it so much sooner, still a sad sorry ‑‑ let's fix that. When there's a request for a Flickr, if we have it in the cash it will return from the cash over wise we go to the network, when when we get response back, we'll send to the cash and the page, this is also good for Avatars, things you want to Cache as you go along, we're going to special case URLs that end in static Flickr.com, take the request, try to take frit the darks fetch it from the network, add it to our Cache, send it to the browser, need be careful, we're adding to the cash for every image request, we'll need the garden at some point. For now, how does that improve things, 3, 2, 3e 1, go. We render quickly, content comes through quickly, this time we have images, all of the images weave seen already, but not this one at the top that's new, that comes through in 11 seconds, and that's pretty good, but we're still dependent on network for the initial API call that tells us which images to display, let's fix that. So this one's a little bit different, the page does a fetch for the API, via the service worker,as everything does, it also goes straight to the Cache, because pages can access the Cache too, it'll render with it, that will trigger the requests for the old images that is also in the cash the service worker goes to the network, gets data back, we do what we do with the images, wend it both to the cash and the page, this is a good point to clean up the Cache, with this pattern it makes two requests, once from the we shall question, once from the network, we get to render quickly with all content but provide up to date content when we find it, the best native apps find it, very few, but the best ones do. Here's where we're at now, we also want to special case K PI.Flickr.com. In that case we'll do, this I'm not going to go through this line by line, this is fetching data, returning it to the browser, this start of Gnarly bit in the middle, pausing data from Flickr, and removing ones from the cash that we don't need anymore this is a little bit Gnarly with promises ES 78 functions make it neater, that's the service worker ‑‑ this makes two request requests so one over on the page side,www.to the Cache, one to network. Afterf the respond come in after the Cac he, we'll update, we'll know an error if they both fail provide data. If the Cache but network fails, we fail silently. That was probably too much code to show on slides. But my point is we're expressing complex behavior using small amounts of code, and the effect of that, let's remind ourself where we started, first visit, takes quite a long time to get the first render, just over a second, then content comes in after over five seconds and then we're waiting forever for the images. Of with service worker and the code we've written to manager the network and Caching, 3, 2, 1, go,we have what looks like a complete view rendered quickly, new data comes in after a few seconds, doesn't disrupt the user, we get the image, we shaved a second off our first render, over 30 seconds for what looks like a complete view. You can get content on the screen in a fraction of a second whether you have a fast, slow or no connection, it doesn't matter this catches up to native. First up, push, something I depend on for many apps before we look at code, going to give a live demo a go, which is (Laughing) see how this goes. Remi, could you help me with this? So ... Remy, you're going to send a chat in there, but not until we have something on the screen. > Huh… I got it by the way… > Fine ‑‑ > It's pretty good. > You’re enjoying your morning so far, was breakfast good? > Yes > I didn't breakfast, I was afraid I might throw it up. (Laughing) > Oh, there we go. This is a simple chat App, this is running in an internal build of Chromium, but based on actual speck work. If you could type in any message in there. > Oh, that's nice, thank you whoever tweeted that, oh, that's lovely, no one tweet anything rude right now. > How's the WiFi holding up? I guess it's ‑‑ > Let's refresh that. Go again.Ed oh, that's a disaster, isn't it I'll refresh this one as well. > Go again, if not, we'll just babe don it ‑‑ > You say don't swear, > Yes, but it's great because it's not going to display, so ... well, agreement tweets, which is a good sign. Oh, this worked like five minutes ago. No, we might just have to aBonn don it. I'm going to drop on to roaming and see if that helps. > Restart Chrome oh, that's a good idea. That normally fixing everything. We're using fire fox here to send the messages, so I can always blame them. Give it one more go, if not, we'll just bane don it. Yes,thank you Remy! (Applause) no, stay. That's ‑‑ we've seen that happen before, this is nothing new, what I'm going to do now is I'm going to close Chromium completely, int browsers not open at all. No recent apps on. So ... many Remy would you care to send another message. Now, what we're getting here, this is a push notification using open web features, and completely native notification, the browser was closed started up the service worker in the background and we got a push notification, because we're using native notification, it appeared on multifamily watch as well just using the open web. (Applause) Remy's birth day as well! Can we switch over to the laptop, is that possible (Happy birthday, to you ‑‑ happy birthday to you. Happy birthday, happy birth dear Remy, happy birthday to you! (Applause) > Brilliant. So ... right, I'm hideously running over now, the way we coded that, it's just a standard, from your page, you register for push messaging, we'll give you the details like the ID and end point where to send messages, but when that actually, when that's called you gel get an vent in the service worker, you'll get to do what you want at this point, look at data, update cache, show notification, once again, you get to did what you want, in that case you can navigate to that page, refocus an existing tab. Background sink is similar, you don't need a service operator for that, sometime late your fire an vent in the service worker to do something for me that I was unable to do earlier. These things require use permission, of course, they'll be told of this. > You have ten minutes. > I have ten minutes, oh,I'm going to tell you about how to code push and Sythisc, then (Laughing) okay, how did that demo work, Jack? Well, I'll tell you. From the page you call navigator.serviceWorker.ready that gives you the registration ‑‑ navigator.serviceWorker ‑‑ on our registration we call push.register, that gives you the details and you post those to the service, you'll associate that with the current use their will give you the end point information where you'll send the information. For home, GSM, Google Cloud messaging, every browser can use their own, you'll need an account set up with the different push messaging providers the data you'll send to these things will be exactly the same, you'll just have to know which way you're sending it, which will be a URL, when the user receives a message, you get a push event and you have a look to see what kind of data, I'm going to react to that, I'm going to do ‑‑ after this I'll show a notification. Something, this is something that native, even the really best native apps, they get it wrong, often I'll get a tweet, I won't notice it when it around arrive, on the under ground I'll see the notification, I'll click et, I'll get nothing because they haven't cached that data off line. You get an vent when you get a click notification and you do what you want, usually navigating to the page, give a we to enumerate the client, which there pages within your scope, look at theme them, see if they're focused, hidden, hang on, there's already a window that has focus, so I don't need to show a notification or I don't need to navigate anywhere,I can determine that stuff ahead of time. What about background Sync, lets you wake up the service worker at some vague point in the future to do whatever you want this is a bit similar to push, it's a lot simpler, if you try to send an e‑mail but the user has no connection, the user is down it fails, you can saver it somewhere, IDB or another cache AI, then register for a Sync event, that triggers a permission dialogue, then, sometimes later when the user has good connectivity, you get a Sync vent, if the ID empty in‑box, get the out box and try to send all the e‑mails, in this pattern, it works similar to installer event, if you pass the event ‑‑ it will reschedule. If we fail to send the e‑mail it will be scheduled for later this is registering for a single Sync event, you ask for ones on an interval as well, use updating train did that that that the background, the ‑‑ is a minimum, when things happen determined heuristically, if you register for a Sync once day and we know the user looks allot your App like about 9:00 in the morning, we can schedule the Sync for 10‑9, and coalescing it with other sink events. With service worker we gain a lot of the features that make native superior, butane the bits that keep the web super your, the instant on, no install required, open platform. Chrome is going to start chipping this stuff this year, it's already if canary, it'll go to stable this year, fire fox actively developing, Microsoft is investigating it, we haven't heard anything from apple, but that's not unusual at this stage, it's designed to be an enhancement, I mean no browser is going to have it on the first visit > Have to prepare, use basic object detection you can give the benefit to the browsers that support it, which is a lot of users in chrome's case. It doesn't turn push messages into ‑‑ it gives you nothing for free, but it treats you like an adult, gifts you the moving parts and do what you want, make things faster, work off line, create new features trance code a video former using streams, turn build a client side Wik I, do it in a way this' unique your App, the way that gives the best user experience. I am heavily biased. I think this changes what the web is capable. Let's build some cool stuff with it. Thank you very much (Applause) Edit transcript via pull request.