By now, most Front End Devs will be aware of the idea of Progressive Web Apps (incidentally launched as a concept at the 2015 Code conference by keynote speaker Alex Russell).
The key enabling technology of “PWAs” is Service Worker, which brings offline capabilities, properly functional caching (sorry AppCache, it’s you, not me) and enables engaging new features like Web notifications, and the ability to add a Web app to the user’s homescreen.
So all this magic must be really complex to implement? Think again.
Marcos has been exploring offline web technologies offline, in a standards-based way, for a decade.
An early approach was W3C Widgets, which went on to become Cordova.
Another attempt was Firefox OS, but it didn’t pan out the way Mozilla hoped.
Out of that effort and the widgets standard, the service worker technology emerged.
The Web Platform Incubator Community Group also came about as a result of this work.
IE6 had 90% of the market, and its behaviour went on to become the default HTML standard.
The DOM influenced the creation of many APIs that were not very good, which led to setting some perimeters and giving those to developers to make their own APIs.
This in turn led to the Extensible Web Manifesto.
Service workers embody those principles: from simple things, you can build complex systems.
The service worker is really just a glorified event handler.
The life cycle of a service worker:
- when you register, you get an Install event that lets you view cache, check for updates
- when it wakes up, you get the Activated event
- when the page tries to get something, Fetch is invoked, and you can manipulate that
- for push notifications, you get a Push event and an object with a little bit of data
- then background Sync is implemented in Chrome and on the way in Firefox
The registration object mirrors the life cycle, so you can register for Push notifications, and implement a Push Server, for example.
One weird trick is that most of the APIs are available on the Window object, which can remove some of the Service Worker setup pain and lets you get up and going.
The building blocks of the Service Worker include the Fetch API, Cache API, Notifications, Push API and more, which can be used on the Window object or the Service Worker.
A Fetch Request returns a Promise and that Promise has a Response, which you can work with.
The Request object takes a number of options that let you control what it does.
The Response object has a number of parts that give you information and let you take action.
All of the APIs involved are deliberately simple but powerful.
The Body mixin provides additional methods you can call.
This process addresses some of the hardest things in computer science, like cache invalidation, naming things and cache volatility.
Go, make stuff!