We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Using Service Workers in Ember

00:00

Formal Metadata

Title
Using Service Workers in Ember
Title of Series
Number of Parts
37
Author
License
CC Attribution - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
Service Workers are now available in browsers but why should we as Ember developers care about them? In this talk we will examine some of the common use cases for Service Workers and patterns for implementing them in your Ember applications.
13
Thumbnail
07:51
VideoconferencingCodeService (economics)Service (economics)NumberComputer animationLecture/Conference
Source codeWeb browserDemosceneService (economics)Web 2.0Point (geometry)EvoluteWeb applicationMeeting/Interview
1 (number)Traffic reportingSoftwareInformationMultiplication sign
Row (database)TrailBinary fileInformationPhysical system
InternetworkingMeta elementConnected spaceInternetworkingSet (mathematics)InformationUniform resource locatorHospital information system
Open sourceService (economics)Open sourceCartesian coordinate systemHospital information systemUsabilityProjective planeComputer animation
InterprozesskommunikationCartesian coordinate systemBitWeb applicationBootstrap aggregatingService (economics)Process (computing)MereologyWater vapor
Cache (computing)DialectWeb browserService (economics)Dependent and independent variablesWeb applicationPoint (geometry)Cache (computing)Key (cryptography)Bootstrap aggregatingDeclarative programmingMereologyMobile appGame controllerCartesian coordinate systemWeightSurfaceDivisorElectronic mailing listHash functionOrder (biology)
SoftwareWeb browserFlow separationService (economics)CodeMobile appProxy serverPower (physics)Software developerLevel (video gaming)Computer animation
Cache (computing)Multiplication signSoftware developerGame controller
Source codeThread (computing)Web browserProcess (computing)StatisticsThread (computing)Level (video gaming)Game controllerService (economics)MereologyBitProcess (computing)Web 2.0WordSoftwareStapeldateiCartesian coordinate systemComputer animation
Cache (computing)Arithmetic meanMessage passingService (economics)Scripting languageMobile appContext awareness
FreewareEncryptionAutomationCryptographyAreaService (economics)Engineering physicsEncryptionLocal ringComputer animation
Service (economics)TrailService (economics)WebsiteDifferent (Kate Ryan album)InformationOrder (biology)Web browser
Service (economics)Event horizonMessage passingInformationOpen setSoftware developerView (database)Computer wormLimit (category theory)Menu (computing)Link (knot theory)Dynamic random-access memoryUser interfaceCurvatureLatent class modelGame controllerSource codeAttribute grammarObject (grammar)VideoconferencingWhiteboardInstallation artProjective planeService (economics)Speech synthesisCartesian coordinate systemVideo game consoleSource codeInstallation artCache (computing)FreewareMobile appSoftware developerShift operatorDependent and independent variablesGraphical user interfaceControl flowCASE <Informatik>Adventure gameGame controllerLevel (video gaming)CodeDemosceneDemo (music)Different (Kate Ryan album)Right angleView (database)Product (business)Process (computing)FrequencyCuboidMultiplication signWeb browserSlide ruleEndliche ModelltheorieScripting languageNumberComputer animation
Color managementComa BerenicesAreaSupercomputerHill differential equationHost Identity ProtocolWeb pageSoftware developerAdventure gameVideo gameGame controllerHydraulic jumpMereologyService (economics)NeuroinformatikReading (process)Computer animation
Service (economics)RobotSoftwareService (economics)Adventure gameScripting languageCASE <Informatik>Confidence intervalProcess (computing)Java appletLibrary (computing)Mobile appMathematicsContext awarenessRevision controlDefault (computer science)Computer fileMereologyAdditionConfiguration spaceMedical imagingSystem callUniform resource locatorBuildingServer (computing)Cache (computing)Computer animation
Cache (computing)Computer networkDefault (computer science)Service (economics)Service (economics)Electronic mailing listDifferent (Kate Ryan album)Strategy gameSoftwareComputer configurationComputer-assisted translationGame controllerPattern languageComputer animation
Router (computing)Computer networkService (economics)CodeMobile appDirectory serviceComputer fileRoutingData structure
InternetworkingError messageConnected spaceService (economics)Context awarenessInternetworkingMobile appLine (geometry)CASE <Informatik>
Source codeUniform resource locatorComputer configurationSystem callMobile appNetzwerkdatenbanksystemLatent heatSoftwareDatabaseRoutingService (economics)CodeBitLocal ringProcess (computing)Web browserCASE <Informatik>Multiplication signSource code
Service (economics)Server (computing)Source codeInternetworkingComputer networkConnected spaceEmailServer (computing)InternetworkingMobile appConnected spaceDenial-of-service attackWeb-DesignerMoment (mathematics)MappingVideo gameComputer animation
Source codeServer (computing)Computer networkService (economics)InformationPoint (geometry)Service (economics)Type theoryWeb browserMobile appComputer wormConnected spaceRow (database)InformationSoftwareSound effectComputer animation
Uniform resource locatorDependent and independent variablesLocal ringInternetworkingServer (computing)Line (geometry)WordService (economics)Metric systemResponse time (technology)SoftwareSoftware protection dongleUniform resource locatorConnected spaceField (computer science)ModemMultiplication sign
Source codeService (economics)Cartesian coordinate systemFormal languageIntelligent NetworkThread (computing)Computer animationLecture/Conference
BefehlsprozessorSource codeWeightService (economics)Web 2.0Mobile appThread (computing)TouchscreenMultiplicationMassFisher's exact testProcess (computing)Graph (mathematics)NumberLecture/Conference
Subject indexingGraphical user interfaceSoftware testingSurfaceWeb browserInsertion lossDatabaseLocal ringDataflowService (economics)Patch (Unix)ExpressionEntire functionFiber bundleDependent and independent variablesSource codeObject (grammar)Annulus (mathematics)Demo (music)WindowView (database)Execution unitScalable Coherent InterfaceInterior (topology)Lemma (mathematics)Inclusion mapMathematicsService (economics)Confidence intervalLocal ringServer (computing)Product (business)Mechanism designRight angleUnit testingWeb browserNear-ringMessage passingFacebookMobile WebInternet service providerConnected spaceSynchronizationMobile appStress (mechanics)Group actionProjective planeDatabaseSoftware testingInsertion lossDirected graphNumberVolumenvisualisierungLine (geometry)AdditionHand fanSingle-precision floating-point formatSubject indexingParticle systemComputer animation
Sign (mathematics)Service (economics)ImplementationRevision controlWeb browserSource codePlanningWeb browserOperator (mathematics)Subject indexingService (economics)
BlogCache (computing)Service (economics)Web browserCategory of beingSource codeGraphical user interfaceService (economics)Point (geometry)Complete metric spaceCartesian coordinate systemMereologyCombinational logicCore dumpWeb browserCache (computing)Graphical user interfaceAdditionMobile appQuicksortFamily
Open sourceWebsiteMobile appInformationSlide ruleLevel (video gaming)Computer animation
Slide ruleTwitterSource codeCovering spaceComputer-generated imageryAsynchronous Transfer ModeEuler anglesSet (mathematics)VideoconferencingService (economics)Event horizonXMLComputer animation
Transcript: English(auto-generated)
get started here. So I'm going to talk to you about using service workers in Ember. It was mentioned in the keynote.
And let me start off by saying, I am really excited about service workers. I mean, I am freaking excited, just like my friend Kristen Wiig here. And here's why. So I believe that service workers are the next evolution in what we can do in a browser. If you think back to the early 2000s,
when XHR came out, it really changed the landscape of what a web app could be. I believe we're at that same vantage point now, where we're going to see service workers really change what we can do with our web apps.
So let me start by telling you how I started working with service workers. So for me, it all started with kids, like the ones you see here. So I work for a nonprofit called Cure International. And we provide lifesaving care to kids in 30 countries in the developing world. And for the last six years, we've
been developing innovative technology solutions, including real-time reporting of our kids in the hospitals. But we realized we were missing something as an essential tool across our network. And that was a hospital information system. We needed something so you provide better oversight of the care taking place
in our hospitals and clinics. And historically, the way we've kept track of everything is through paper records that then get loaded into these bins you see here and transported to remote clinics. It's kind of really clunky. And as a technologist, I know we can do a lot better.
Working in the developing world, we also have our own set of challenges. And the most challenging thing is internet connectivity. So in some locations, connectivity is either poor or nonexistent. So when we examined the existing solutions for a hospital information system, we couldn't find anything out there
that really solved developing world challenges. So we decided to build our own. And we built something called Hospital Run. It's a hospital information system built for the developing world, for hospitals in the developing world. And it's an open source solution that we built for the approximately 14,000 hospitals
in the developing world that need a solution like this. We built it with Ember, of course. We built it for offline and online use. And we have an intentional focus on usability. So when service workers became available, it became immediately clear to me that they were something that would be very useful
for Hospital Run. So as I talk about service workers, I'll be highlighting how they've been helpful in our project, as well as to call out uses in other Ember applications. So let me start off with what are service workers? It was mentioned in the keynote. You may know some things about them,
but let's read what the spec says. The spec says, this is a method that enables applications to take advantage of persistent background processing, including hooks, to enable bootstrapping of web applications while offline. So let's break that down a little bit. So the second part of the definition says that it's a bootstrapping of web applications while offline.
So if you've heard of service workers before, you probably have heard this offline story. And in fact, one of the key features of service workers is that they allow your app to run offline. But to say that service worker, excuse me, service workers, however, were not the first browser feature to allow you to do this.
Our friend app cache, which has been referenced already, and is such a wonderful thing, was the de facto way of doing offline. And in fact, as was pointed out in the keynote, is still the way to do offline. But there is a lot of pain points in it. And a lot of that has to do with the fact
that it's a declarative. It doesn't really give you the control that you need. And service workers were kind of created in part as a response to the horribleness of application cache. But just talking about offline with service workers is just skimming the surface. We're just getting started here.
So service workers really give you, as a developer, the power. So one way to think of a service worker is as this network proxy that allows you to control what happens with every network request. And because service workers are allowing you to interface at the network level, you can run them on top of your existing apps
without changing your existing code. So that's an important thing to keep in mind. And there's several complementary browser features that can be used with service workers, and they're important concepts. And the first one is the cache API. So with this API, developers have ultimate control
of what gets cached and when. And you can also reach into that cache and pull things out at any time you want to. So really, what you're getting here is what used to be only browser internals is now available to you as a developer, and I think that's really awesome. Another feature that is complementary
to service workers is fetch. And you can kind of think of fetch as like XHR with promises. It gives you the same kind of level of control of being able to pull things from the network, and it's the only way of doing it in a service worker. You can't use XHR inside of service workers.
So getting back to our definition of service workers, there's a part that I skipped, and that's the first part that talks about this idea of persistent background processing. And this is an important thing to remember. Service workers are running in the background. But what exactly do we mean that it's running in the background? Well, when service workers were first introduced,
they were called navigation controller. But that name was changed to include the word worker, and that part is very significant because service workers are like web workers in that they run in a separate thread. So you think of your typical JavaScript application, it's single-threaded,
this is running in a separate thread. And this will lead us to some performance implications that I'll get to in a bit. So because service workers are workers, it means that they're essentially sandboxed. They're running in their own global script context, meaning that they don't have direct access to your app's code, but they do have ways to communicate outside
with post messages and even with the cache API. There is one important caveat to using service workers, and that's that they're HTTPS only. This doesn't apply for local hosts, so any development, you don't have to worry about it. But the good news here is, anymore we really shouldn't be concerned
about the cost of HTTPS, especially when you have services like Let's Encrypt and even AWS offering free certs. We really don't have an excuse to not run HTTPS anymore. So that's kind of a quick overview of what service workers are. If you wanna know more about some of the details
of service workers that I won't get into in this talk, I wanna mention a couple resources. The first one is this site is service worker ready. This has some great overview information, as well as kind of keeping track of, in different browsers, what features are available and kind of the status of things, so it's really helpful that way.
Another useful resource is Mozilla put together the service worker cookbook, and they kind of break down these different use cases with these live demos and then show you the source code. So it's a really easy way to kind of learn kind of behind the scenes how service workers work. So I also wanna mention that the Chrome Developer Console
is a really useful tool. You can debug your service worker code just as easy as any other JavaScript application. You have the same tools. And the other piece that's in the Developer Console is a view into the cache. Now this is, again, because caching used to be
like a browser internal thing, it wasn't really all that easy to see into it, but with the cache API and developer tools, you really can kind of look into it. And speaking of debugging, I got trolled by something the other day, and something unexpected happened. So I was working on this project with service workers,
and I did a command refresh. I had this habit of hitting like command shift refresh, and I noticed that my service worker app suddenly wasn't available when my app was offline, and I thought, shoot, like I broke something. I really like just messed up my code. Well, it turns out the spec actually says
if you do a hard refresh, it basically disables the service worker. So that's just something to keep in mind as a developer. So hopefully this kind of gives you a high level understanding of what service workers are and kind of the landscape, but we're here to talk about service workers in Ember. So let's start talking about that.
So last year, Tom Dale said this, that service workers should be something that Ember apps get basically for free. I agree, and I just so happen to be working on something around that time, and that was broccoli service worker. So out of the box, broccoli service worker
will set up your production builds to include a service worker that will make your application available offline, and it's completely free. Isn't that awesome? Completely free, yeah! So that's broccoli service worker. So that's it really. Like all you need to do is install broccoli service worker, and you're fine.
I can end my talk right now. We can go have our break, and we'll be good. Well, we're not done yet. Remember that I said that service workers were created in response to the horribleness of application cache. So one of the particular main issues with application cache is that it didn't give developers as much control over what happened. Service workers, on the other hand,
are like choose your own adventure books. So when I was a kid, I remember reading these books that were kind of like a computer game, where you get to a part of the story, and it would be like you have to decide should Johnny jump through the creek, or should he run away, and depending on what you did,
different outcomes would happen. Now I don't remember this one about you are a shark, but it sounds really awesome. And actually, I read the Google reviews on it, and one guy, he was a little disappointed because you can only be a shark in three pages, but it still might be an entertaining read. Anyway, service workers give you as a developer
control over what happens. So let's see how we can affect that control with broccoli service worker. So there's several levels of choose your own adventure with broccoli service worker, and the first one is through simple configuration. So in your config file for your app, you can configure some things like pre-cache URLs.
So by default, your whole app is pre-cached. That means all your assets, all the JavaScript images, that kind of thing gets pre-cached. If there's additional resources that you wanna pre-cache and always serve them from the cache, you can do so. And the cool thing is because broccoli service worker
is part of your build process and part of the live reload, is a new version of the service worker gets introduced when you make changes, so you don't have to worry about that data getting stale. It automatically is getting refreshed. So you can, with confidence, pre-cache your whole app. There's things like a fallback.
So the use case here is if I'm offline, instead of rendering this server out, go render this other one. And then we can do things like network first URL. So something like an API call where we wanna get the freshest data we can, we use a network first request
and if it's offline, it'll fall back to the cache. And then this last piece, include files, will let us bring in, remember I said the service worker's script, it has a different context than your app. So if you need to bring in pieces of your app or in this case, I need to bring in a PouchDB library,
I can do that through the config. So Broccoli service worker includes Google's service worker toolbox and this is really a useful tool in working with service workers. And this allows us to do express style routing with predefined network strategies.
So you can see here, there's kind of a list of different network strategies that are useful in service workers, so you may have data that you wanna get the freshest, so you always go to the network first but you wanna fall back to cache or maybe there's stuff that you just want it to be the fastest, so there's a solution,
there's a recipe to do to pull back the fastest data. So these options are available to you through config, so you can just specify these paths, use these strategies. But if you wanna have finer grain control,
what you can actually do is add files to the service worker's directory in your app. And any file in this directory will automatically be included in the service worker that's built for your app. So you can continue to use the service worker toolbox here to do some of the heavy lifting involved with service workers or you can roll your own code.
So it's a useful way to bring in your own code into a service worker if you decide to go that route. So as I mentioned earlier, one of the challenges we face with hospital run is working in context where internet connectivity can be spotty to non-existent.
And because this is the case, we need to be able to handle a user's lack of connectivity gracefully in our app. We didn't want them to see the little dinosaur or even to run into some kind of error situation. We wanted to be able to handle it gracefully. And so just adding broccoli service worker
lets our app run offline, but it doesn't say anything about what do we do with data, how do we handle that? And we need a way to be able to handle the user trying to save or access data offline. So in our case, to handle this particular issue, we added code to handle specific network database calls.
So we set up routes where what we're doing is we intercept that call and instead of, first we try to get it from the network. And if that call fails, we then pull back and grab it from a local PouchDB database.
And what's really great about this is the process is seamless to both the user and to your app. The app thinks it's always getting a successful network request, even when you're offline, because all that's handled in the service worker. And I think that's just, it blows my mind a little bit that we can do that in a browser these days, but it's awesome.
So you may be thinking offline isn't something you need to care about, though I'm hoping after Tom and Yehuda's keynote, you do realize it's something you need to care about. But let me give you a couple reasons to think about handling offline in your app. The first thing to think about is, not only your users being offline, but what happens when your server's offline?
Be it, you know, a DDOS or just someone screwing up. Our servers do go offline occasionally. So if we can handle offline from both the server and the user, I think that's a win. A second reason to consider offline is our friend LiFi.
Now I know you've all experienced this, that moment where you're connected to WiFi, maybe even at this conference, and you don't really have an internet connection. We can take that pain away from our users, and I would suggest we should take away that pain from our users. Also, while native apps have been able to do offline for a while,
there's still a lot of native apps that don't do offline well. We as web developers have an opportunity to do offline well, and to give our users a great experience, whether they have a great internet connection or they have a really bad one. So maybe offline isn't a concern for you,
but you may be in a situation where you're writing mobile apps and you have to worry about 2G users or users who have a throttle connection. One of the things we do with a service worker is adapt our payload based on the network type.
We have some information available in the browser to say, okay, it looks like they're on a 2G connection, so instead of fetching 100 records, I'm only gonna fetch 10. So we can do things like that in a service worker. And along those lines, for hospital run, we wanted to be able to monitor
response times from the server. So some of our locations, the Wi-Fi may not be that great or internet connectivity may not be that great, but if we can individually monitor for each user, okay, what's your experience like, we gain some metrics to be able to say, okay, well maybe in the hospitals, we need to improve the Wi-Fi network
or we need to make sure that when they go out in the field, they have enough, like a 3G dongle that they can use to get that connectivity. So we time out, optionally time out the response times. So that's kind of looking at service workers from the network side of things,
but there are some other things that we can do with service workers. So as I mentioned earlier, because service workers run in a separate thread, there are opportunities to improve performance using a service worker. So typically, our Ember applications are single-threaded, kind of like this guy here. But with a service worker,
now wait, wait, wait. Now, I'm pretty sure I've never seen a blue screen of death on a JavaScript app, especially an Ember app, but the reality is our apps are single-threaded
and with a service worker or a web worker, we can use multiple threads in our Ember app. And one of the performance bottlenecks that we had in hospital run was syncing between this local Pouch database in the browser and a CouchDB server. And it turned out that IndexedDB,
which is used by PouchDB, it blocks the DOM and it can affect performance. So it wasn't a great solution. So what we ended up doing was moving that synchronization into the service worker. We immediately saw performance gains. In fact, here's a quote from Nolan Lawson, who's one of the guys behind PouchDB, and he said, yeah, put it in a worker, he recommends it.
So I think that's pretty cool. So some people have gotten really creative about what they're doing in service workers. And I found this example where someone is running an express server inside a service worker. So they're, in essence, turning the service worker into a server. So you could have an app that's basically serverless
beyond that first render, beyond that first delivery. And you could do that in an Ember app today. So I think that's pretty cool. So we've seen some examples of how service workers can be used in Ember apps today. But as we think about the future of Ember and service workers, where are we headed?
So one of the additional features that service workers enable are native push notifications. And I think this was touched on in the keynote. And the thing that we're gonna be able to do here is provide native push notifications to our users, which I think is pretty cool,
giving people that native feel. And you may have even seen this. Facebook is actually using this in production now. And it's kind of pretty cool. So another forthcoming feature enabled by service workers is background sync. And the idea here is that actions can be deferred
until a user has stable connectivity. So particularly in mobile. So in this particular example, what happens is the user goes offline, they send a message while they're offline, and then they go back online, and the message is then sent. And this provides like a queuing mechanism that certain Ember apps are gonna benefit from,
where instead of having to build some off-the-shelf queuing mechanism to sync offline updates, the browser will do it for you. So I think that's pretty exciting and that's coming soon to a browser near you. Right now, there's not a great way to test service workers in Ember,
particularly if you're talking about command line. So you're running your Travis builds, Phantom knows nothing about service workers. So it's kind of a gap right now, but the fortunate thing is there's groundwork in projects like this service worker unit testing
that I think we can take advantage of in Ember. So as was mentioned in the keynote, service workers aren't in every browser, but we're seeing positive traction in the browser vendors. Microsoft in particular is working on it, and I have confidence that,
especially with some of the changes that have been happening in Microsoft, that they will end up getting this done. And Opera, or sorry, Opera. Opera does support service workers. Safari is considering doing service workers, and they've actually indicated in their five-year plan that it's something that they should do.
Now, Yehuda made some reference to this of they may not ever do it, and in some days, I feel that way, but the more I think about it, I think service workers is such an evolutionary step in browsers that I do believe down the road, Safari is going to embrace it,
and just like AppCache and IndexedDB made their way into Safari, we will see service workers in Safari. This was, I think, mentioned in the keynote as well. Application cache is deprecated in Firefox, and they've actually talked about removing support for it.
So while I think application cache is the way to do things now, or at least it needs to be part of your story, keep in mind that that application cache will at some point go away. So we need to think about how do we build apps
that maybe use service worker where possible, and then fall back to AppCache, which by the way, the service worker spec says that if a service worker's running, it'll ignore AppCache. So the browser vendors have kinda kept that in mind. So really the story is you could do both together
and end up with something that's gonna cover, I think, what was it, 90% of the browsers. Chrome's following Firefox's proposal, so they're kinda following in their steps. So it's just something to keep in mind. So lastly, when considering the future of Ember
and service workers, I really think we need to start thinking about what it means to bring them into Ember core. And I was encouraged by what I heard in the keynote because I know that Tom and Yehuda think that this is important as well. So because Ember data is typically network-centric, it seems that it makes sense
that we would take advantage of the multi-threading there to speed up things with service workers. And I think that we will use service workers in combination with Fastboot to be able to render things really quickly and just give a complete offline story
that really is better than native. So that leads me to ask you a question. As you think about what we currently can do with service workers and what's coming in the near future, I wanna ask you to consider how you can use service workers and perhaps contribute work to Ember core
or to additional Ember add-ons. So as I mentioned at the beginning of my talk, I believe that service workers are a huge evolutionary step forward for browsers and we should be taking advantage of that. And one more thing. So Hospital Run is looking for volunteers to help us build an awesome app for the approximately 14,000 hospitals
in the developing world that need a solution like this. So you can find out more information at hospitalrun.io. In your swag bag, you all receive a hospital bracelet that has our website on it, so you shouldn't forget it, so thanks. And that's it, thanks.