Access caches from the window
With all of this work we've been doing outside of the
window, you might think that
Cache instances can only be accessed in the service worker scope. The fact is that you can access
Cache instances in both the service worker scope and in your web app's traditional code, running in the
window. This makes it easier for the user to directly interact with a service worker cache, or update the user interface based on cache state.
One potential use case is to offer a "save for offline" feature for pages the user may want to read later, but know they may be offline at that time. The Glitch embed below shows how to do this with Workbox.
In the above embed, you can see that the
app.js script writes to the offline cache from the
window context when the "save for offline" button is clicked. In the service worker, the page's static assets are precached for offline access. A
NetworkOnly strategy is used with a special handler that manages offline access for cached pages, and is passed to a
To test the functionality in the Glitch embed, do the following:
- Open a new browser window and navigate to https://save-for-offline-test.glitch.me/
- Click the button that reads Add to offline reading list.
- Open your browser's developer tools in either Firefox or Chrome. If you're using Chrome, go to the application panel. In Firefox, go to the storage panel.
- In either browser's developer tools, you'll see a Cache Storage item in the left-hand pane. Click to expand it. In the offline-cache entry, you should see the page URL you just added in the right-hand pane.
- Click on any other page link at the bottom of the page.
- Toggle offline mode in either browser to simulate an offline connection.
- Click on the link for the page you added to the offline cache. It should appear even though you're offline.
- Click on a link for a page you didn't add to the offline cache. The request will fail.
It's been said before in this documentation, but it bears repeating in this context: be mindful of storage quotas. When users have direct control over what's put in a cache, you may want to enforce a maximum age or number of entries in your service worker cache(s).
This isn't the only use case for working with
Cache instances in the
window. For example, you could predictively prefetch and cache assets you know the user will need to perform a specific action. This would reduce or avoid the latency of downloading those assets on demand.
There are other potentially beneficial use cases—and, since you can interact with
Cache instances in the absence of a service worker, not all of them may require one to be installed.