This sample demonstrates a basic service worker that could be used as-is, or
as a starting point for further customization.
What It Does
Precaches the HTML, JavaScript, and CSS files needed to display this page offline.
(Try it out by reloading the page without a network connection!)
Cleans up the previously precached entries when the cache name is updated.
Intercepts network requests, returning a cached response when available.
If there's no cached response, fetches the response from the network and
adds it to the cache for future use.
You can confirm the service worker's behavior using the
Application panel
of Chrome's DevTools.
What It Doesn't Do
Automatically version any of the precached resources.
You must manually update the CACHES.PRECACHE name to pick up
new versions after updating anything!
Cache-bust the precaching requests.
The cache.addAll() call may be fulfilled with responses from
the HTTP cache, depending on the HTTP caching headers you use. If you
are using
HTTP caching
and unversioned resources, it can be safer to
cache-bust
your precaching requests.
Refresh the entries in the runtime cache.
Once an entry is added to the runtime cache, it's used indefinitely,
without consulting the network to check for updates. If your runtime cache
is used for resources that might be updated, a different strategy, like
stale-while-revalidate
could be more appropriate.
Clean out the runtime cache.
The runtime cache will grow as new resource URLs are requested. In this
example, there are only 5 different images that might be loaded, so the
cache size isn't a concern. If your web app might request an arbitrary
number of unique resource URLs, then using a library like
sw-toolbox
which provides
cache-expiration
is recommended.
Live Demo
The following demo illustrates the service worker's runtime caching by loading
images in response to clicking the button below.
The first time a given image is requested, the service worker will be load it
from the network, but each subsequent time, it will be retrieved from the cache.