Service Worker Sample: Read-through Caching (w/Offline Analytics)

Available in Chrome 40+

This sample demonstrates basic service worker registration, in conjunction with read-through caching. After the service worker starts controlling this page, the first time a specific resource is requested, it's fetch()ed from the network and a copy of the response is stored in the service worker's cache. All subsequent times that the same resource is requested, it's returned directly from the cache.

Note: This is a very aggressive approach to caching, and might not be appropriate if your web application makes requests for arbitrary URLs as part of its normal operation (e.g. a RSS client or a news aggregator), as the cache could end up containing large responses that might not end up ever being accessed. Other approaches, like selectively caching based on response headers or only caching responses served from a specific domain, might be more appropriate for those use cases.

Additionally, this sample will save up any failed Google Analytics /collect pings that fail, and store them in IndexedDB. Every time the service worker script starts up, it will check for any saved requests and "replay" them, by sending them to the Google Analytics server with the appropriate qt parameter set to specify the delta since the ping was created. If that replay succeeds, the request will be removed from IndexedDB, and if it fails (because the network is still not available) then it will be retried the next time the service worker script starts up.

Visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing.