Adding Resources to the Cache
You'll learn: How to populate your cache storage with resources using three key methods: cache.add(), cache.addAll(), and cache.put().
Once you've opened a cache (like you learned in the previous lesson), you need to fill it with the resources your app will need offline. Think of it like stocking a pantry—you're storing copies of files so they're available later, even without a network connection.
The Three Methods for Adding Resources
cache.add(request)
Takes a single URL or Request object, fetches it from the network, and stores the response in the cache. It's like asking someone to grab one item from the store and put it in your pantry.
cache.addAll(requests)
Takes an array of URLs or Request objects and fetches all of them, storing each response. This is your bulk shopping trip—multiple items in one go. If any request fails, the entire operation fails.
cache.put(request, response)
Manually stores a specific Request/Response pair. Unlike add(), you provide both the request and the response yourself. This gives you complete control, useful when you've already fetched something or created a custom response.
How They Work Together
Use addAll() during installation to cache your core app files. Use add() to cache individual resources as needed. Use put() when you have a response object from a fetch operation and want to cache it manually.
All three methods store Request/Response pairs—the cache remembers both what was asked for (the URL/request) and what came back (the response with headers and body).
Key Takeaway: cache.add() and cache.addAll() fetch and store resources automatically, while cache.put() lets you manually store Request/Response pairs you've already obtained—giving you flexible control over what goes into your cache.