Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the size and/or number of elements in a ServiceWorker cache?

ServiceWorker is a new api available in Chrome. One of the many things it lets you do is intercept network requests and respond with a cached version. I'm implementing a "take this offline" button which dynamically adds things to the cache. I'd like to report to the user how much space I'm using, and how many entries I've put in the cache.

Is it possible to query a cache to get the number of items in it? Can I report the total size of things cached in it?

like image 348
Rob Avatar asked Feb 05 '15 05:02

Rob


People also ask

How do I find my cache size?

Right-click on the Start button and click on Task Manager. 2. On the Task Manager screen, click on the Performance tab > click on CPU in the left pane. In the right-pane, you will see L1, L2 and L3 Cache sizes listed under “Virtualization” section.

How do I retrieve data from cache?

You can fetch a custom object from the cache using various overloads of the Get() method by specifying the key of the cache item. The object is retrieved as a template, so it needs to be type-cast accordingly if it is a custom class object.

How much can a service worker cache?

Up to this point Apple has decided to limit the service worker cache storage limit to roughly 50MB. It is actually limited to 50MiB, which equates to about 52MB.


1 Answers

You can do something like the following to find the approximate size of the cache:

// returns approximate size of a single cache (in bytes)
function cacheSize(c) {
  return c.keys().then(a => {
    return Promise.all(
      a.map(req => c.match(req).then(res => res.clone().blob().then(b => b.size)))
    ).then(a => a.reduce((acc, n) => acc + n, 0));
  });
}

// returns approximate size of all caches (in bytes)
function cachesSize() {
  return caches.keys().then(a => {
    return Promise.all(
      a.map(n => caches.open(n).then(c => cacheSize(c)))
    ).then(a => a.reduce((acc, n) => acc + n, 0));
  });
}

There's a few caveats:

  • Counts the size of the response body only. (This could be partially fixed.)
  • Counts non-opaque responses. (This can't be fixed.)
like image 76
mjs Avatar answered Oct 21 '22 02:10

mjs