Pragmatist's Guide to Service Workers
In this repository, you'll find code examples to illustrate the Pragmatist's Guide presentation, given at Smashing Conference, Freiburg, September 2016.
Clone this repository, then:
To run a local web server and see the examples in action, run:
You'll want to use a browser that supports Service Worker; I use Chrome but SW is also supported in Firefox and Opera to differing extents.
Note: These examples, run locally, rely on the
localhost exception to the SSL/TLS requirement for Service Workers.
- Mission 1: Offline message — Respond to
navigationrequests (i.e. requests for HTML documents). Try to fetch from the network, but if that fails, return a
Responseobject that emulates a simple web page with an
- Mission 2: Offline page — Same as before, but instead of returning a self-made Response on fetch failure, cache an offline HTML page during the
installphase and return that upon fetch failure.
- Mission 3: Network strategies — Respond to fetches for content (HTML) and static assets (images) differently. Use a network-first strategy for content and a cache-first strategy for images.
- Mission 4: Application shell — During the
installphase, cache a bunch of static assets that we consider to be our application's "shell". Respond to fetches and look in the cache first for requests for those assets. Once the service worker is installed, you can go offline and continue to "request clouds" (images of clouds).
- Mission 5: Cache naming and cleanup — Use cache-prefixing to manage versioning of a service worker and, during the
activatephase, clean up (old) caches that don't match the new cache prefix. To version-bump, you'd want to change the
- Mission 6: Fancypants — Add a fallback offline image and use a JSON file as a source of URLs to pre-cache during