96Implement a simple Service Worker caching strategy
Problem
A Service Worker can answer requests from a cache. Implement the three classic strategies as plain functions, so they can be tested outside a worker. Each takes a Request and { cache, fetch }, where cache has the Cache API's match(request) and put(request, response):
cacheFirst(request, deps): return the cached response if there is one; otherwise fetch, store a clone in the cache if it is OK (response.ok), and return it. Use it for versioned static assets.networkFirst(request, { cache, fetch, timeout = 3000 }): try the network; if it fails or takes longer thantimeoutms, fall back to the cache; if there is no cached copy either, rethrow the error. Cache successful network responses. Use it for HTML and API reads.staleWhileRevalidate(request, { cache, fetch, waitUntil }): return the cached response immediately if there is one and refresh the cache in the background (pass the refresh promise towaitUntilso the worker stays alive); without a cached copy, wait for the network. Use it for avatars and other content that may be slightly old.
Then write pickStrategy(request): navigations (request.mode === "navigate") and /api/ URLs use networkFirst, URLs ending in .js, .css, .woff2 use cacheFirst, images (request.destination === "image") use staleWhileRevalidate, and anything else returns null (let the browser handle it). Non-GET requests always return null.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Step-by-step
A Response body can be read only once. If you return the response to the page and also put it in the cache, one of them gets an already-used body. Always cache.put(request, response.clone()).
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 3 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.