CacheStorage

This translation is incomplete. Please help translate this article from English

The CacheStorage interface represents the storage for Cache objects.

The interface:

Use CacheStorage.open() to obtain a Cache instance.

Use CacheStorage.match() to check if a given Request is a key in any of the Cache objects that the CacheStorage object tracks.

You can access CacheStorage through the global caches property.

Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.
Note: CacheStorage.match() is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from CacheStorage.keys(), opening each cache with CacheStorage.open(), and matching the one you want with Cache.match().

Methods

CacheStorage.match()
Checks if a given Request is a key in any of the Cache objects that the CacheStorage object tracks, and returns a Promise that resolves to that match.
CacheStorage.has()
Returns a Promise that resolves to true if a Cache object matching the cacheName exists.
CacheStorage.open()
Returns a Promise that resolves to the Cache object matching the cacheName (a new cache is created if it doesn't already exist.)
CacheStorage.delete()
Finds the Cache object matching the cacheName, and if found, deletes the Cache object and returns a Promise that resolves to true. If no Cache object is found, it resolves to false.
CacheStorage.keys()
Returns a Promise that will resolve with an array containing strings corresponding to all of the named Cache objects tracked by the CacheStorage. Use this method to iterate over a list of all the Cache objects.

Examples

This code snippet is from the MDN sw-test example (see sw-test running live.) This service worker script waits for an InstallEvent to fire, then runs waitUntil to handle the install process for the app. This consists of calling CacheStorage.open to create a new cache, then using Cache.addAll to add a series of assets to it.

In the second code block, we wait for a FetchEvent to fire. We construct a custom response like so:

  1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
  2. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using Cache.put (cache.put(event.request, response.clone()).)
  3. If this fails (e.g. because the network is down), return a fallback response.

Finally, return whatever the custom response ended up being equal to, using FetchEvent.respondWith.

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        '/sw-test/',
        '/sw-test/index.html',
        '/sw-test/style.css',
        '/sw-test/app.js',
        '/sw-test/image-list.js',
        '/sw-test/star-wars-logo.jpg',
        '/sw-test/gallery/bountyHunters.jpg',
        '/sw-test/gallery/myLittleVader.jpg',
        '/sw-test/gallery/snowTroopers.jpg'
      ]);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(caches.match(event.request).then(function(response) {
    // caches.match() always resolves
    // but in case of success response will have value
    if (response !== undefined) {
      return response;
    } else {
      return fetch(event.request).then(function (response) {
        // response may be used only once
        // we need to save clone to put one copy in cache
        // and serve second one
        let responseClone = response.clone();
        
        caches.open('v1').then(function (cache) {
          cache.put(event.request, responseClone);
        });
        return response;
      }).catch(function () {
        return caches.match('/sw-test/gallery/myLittleVader.jpg');
      });
    }
  }));
});

This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code.

// Try to get data from the cache, but fall back to fetching it live.
async function getData() {
   const cacheVersion = 1;
   const cacheName    = `myapp-${ cacheVersion }`;
   const url          = 'https://jsonplaceholder.typicode.com/todos/1';
   let cachedData     = await getCachedData( cacheName, url );

   if ( cachedData ) {
      console.log( 'Retrieved cached data' );
      return cachedData;
   }

   console.log( 'Fetching fresh data' );

   const cacheStorage = await caches.open( cacheName );
   await cacheStorage.add( url );
   cachedData = await getCachedData( cacheName, url );
   await deleteOldCaches( cacheName );

   return cachedData;
}

// Get data from the cache.
async function getCachedData( cacheName, url ) {
   const cacheStorage   = await caches.open( cacheName );
   const cachedResponse = await cacheStorage.match( url );

   if ( ! cachedResponse || ! cachedResponse.ok ) {
      return false;
   }

   return await cachedResponse.json();
}

// Delete any old caches to respect user's disk space.
async function deleteOldCaches( currentCache ) {
   const keys = await caches.keys();

   for ( const key of keys ) {
      const isOurCache = 'myapp-' === key.substr( 0, 6 );

      if ( currentCache === key || ! isOurCache ) {
         continue;
      }

      caches.delete( key );
   }
}

try {
   const data = await getData();
   console.log( { data } );
} catch ( error ) {
   console.error( { error } );
}

Specifications

Specification Status Comment
Service Workers
La definición de 'CacheStorage' en esta especificación.
Working Draft Initial definition.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome para AndroidFirefox para AndroidOpera para AndroidSafari en iOSSamsung Internet
CacheStorage
Experimental
Chrome Soporte completo 40
Notas
Soporte completo 40
Notas
Notas Accessible from Window from version 43.
Notas Accessible from WorkerGlobalScope from version 43.
Edge Soporte completo ≤18Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 11.1WebView Android Soporte completo 40
Notas
Soporte completo 40
Notas
Notas Accessible from Window from version 43.
Notas Accessible from WorkerGlobalScope from version 43.
Chrome Android Soporte completo 40
Notas
Soporte completo 40
Notas
Notas Accessible from Window from version 43.
Notas Accessible from WorkerGlobalScope from version 43.
Firefox Android Soporte completo 44Opera Android Soporte completo 27Safari iOS Soporte completo 11.3Samsung Internet Android Soporte completo 4.0
Notas
Soporte completo 4.0
Notas
Notas Accessible from Window from Samsung Internet 4.0.
Notas Accessible from WorkerGlobalScope from Samsung Internet 4.0.
delete
Experimental
Chrome Soporte completo 40Edge Soporte completo 16Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 11.1WebView Android Soporte completo 40Chrome Android Soporte completo 40Firefox Android Soporte completo 44Opera Android Soporte completo 27Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 4.0
has
Experimental
Chrome Soporte completo 40Edge Soporte completo 16Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 11.1WebView Android Soporte completo 40Chrome Android Soporte completo 40Firefox Android Soporte completo 44Opera Android Soporte completo 27Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 4.0
keys
Experimental
Chrome Soporte completo 40Edge Soporte completo 16Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 11.1WebView Android Soporte completo 40Chrome Android Soporte completo 40Firefox Android Soporte completo 44Opera Android Soporte completo 27Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 4.0
match
Experimental
Chrome Soporte completo 54
Soporte completo 54
Soporte parcial 40
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
Edge Soporte completo 16Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 41
Soporte completo 41
Soporte parcial 27
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
Safari Soporte completo 11.1WebView Android Soporte completo 54
Soporte completo 54
Soporte parcial 40
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
Chrome Android Soporte completo 54
Soporte completo 54
Soporte parcial 40
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
Firefox Android Soporte completo 44Opera Android Soporte completo 41
Soporte completo 41
Soporte parcial 27
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 6.0
Soporte completo 6.0
Soporte parcial 4.0
Notas
Notas The options parameter only supports ignoreSearch, and cacheName.
open
Experimental
Chrome Soporte completo 40Edge Soporte completo 16Firefox Soporte completo 44
Notas
Soporte completo 44
Notas
Notas Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.
IE Sin soporte NoOpera Soporte completo 27Safari Soporte completo 11.1WebView Android Soporte completo 40Chrome Android Soporte completo 40Firefox Android Soporte completo 44Opera Android Soporte completo 27Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 4.0
Secure context required
Experimental
Chrome Soporte completo 65Edge Soporte completo ≤79Firefox Soporte completo 44IE Sin soporte NoOpera Soporte completo 52Safari Soporte completo SiWebView Android Soporte completo 65Chrome Android Soporte completo 65Firefox Android Soporte completo 44Opera Android Soporte completo 47Safari iOS Soporte completo SiSamsung Internet Android Soporte completo 9.0

Leyenda

Soporte completo  
Soporte completo
Sin soporte  
Sin soporte
Experimental. Esperar que el comportamiento cambie en el futuro.
Experimental. Esperar que el comportamiento cambie en el futuro.
Ver notas de implementación.
Ver notas de implementación.

See also