Cache

https://news.ycombinator.com/rss Hits: 4
Summary

This code snippet is from the service worker selective caching sample. (see selective caching live) The code uses CacheStorage.open() to open any Cache objects with a Content-Type header that starts with font/. The code then uses Cache.match() to see if there's already a matching font in the cache, and if so, returns it. If there isn't a matching font, the code fetches the font from the network and uses Cache.put() to cache the fetched resource. The code handles exceptions thrown from the fetch() operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code. The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name. The code also deletes all caches that aren't named in CURRENT_CACHES. In the code example, caches is a property of the ServiceWorkerGlobalScope. It holds the CacheStorage object, by which it can access the CacheStorage interface. Note: In Chrome, 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. const CACHE_VERSION = 1; const CURRENT_CACHES = { font: `font-cache-v${CACHE_VERSION}`, }; self.addEventListener("activate", (event) => { // Delete all caches that aren't named in CURRENT_CACHES. // While there is only one cache in this example, the same logic // will handle the case where there are multiple versioned caches. const expectedCacheNamesSet = new Set(Object.values(CURRENT_CACHES)); event.waitUntil( caches.keys().then((cacheNames) => Promise.all( cacheNames.map((cacheName) => { if (!expectedCacheNamesSet.has(cacheName)) { // If this cache name isn't present in the set of // "expected" cache na...

First seen: 2025-09-04 17:01

Last seen: 2025-09-04 20:03