--- title: CacheStorage.open() slug: Web/API/CacheStorage/open tags: - API - CacheStorage - Experimental - Method - Reference - ServiceWorker translation_of: Web/API/CacheStorage/open ---

{{APIRef("Service Workers API")}}{{SeeCompatTable}}

open() метод из {{domxref("CacheStorage")}} интерфейса возвращает {{jsxref("Promise")}} который резолвится в {{domxref("Cache")}} обьект с соответствующим cacheName (именем тега кеша).

Note: If the specified {{domxref("Cache")}} does not exist, a new cache is created with that cacheName.

Синтакс

caches.open(cacheName).then(function(cache) {
  //обрабатываем кеш например: cache.AddAll(filesToCache); где filesToCache = ['/mypic.png', ...]
});

Возвращает

{{jsxref("Promise")}} который резолвится в запрашиваемый {{domxref("Cache")}} обьект.

Параметры

cacheName
Имя (тег) кеша заданное заранее которое необходимо открыть.

Примеры

This code snippet is from the MDN sw-test example (see sw-test running live). Here we wait for a {{domxref("FetchEvent")}} to fire. Then we construct a custom response like so:

  1. Check whether a match for the request is found in the {{domxref("CacheStorage")}} using {{domxref("CacheStorage.match")}}. If so, serve that.
  2. If not, open the v1 cache using {{domxref("CacheStorage.open")}}, put the default network request in the cache using {{domxref("Cache.put")}} and return a clone of the default network request using return response.clone() — necessary because put() consumes the response body.
  3. If this fails (e.g., because the network is down), return a fallback response.
var response;
var cachedResponse = caches.match(event.request).catch(function() {
  return fetch(event.request);
}).then(function(r) {
  response = r;
  caches.open('v1').then(function(cache) {
    cache.put(event.request, response);
  });
  return response.clone();
}).catch(function() {
  return caches.match('/sw-test/gallery/myLittleVader.jpg');
});

Specifications

Specification Status Comment
{{SpecName('Service Workers', '#cache-storage', 'CacheStorage')}} {{Spec2('Service Workers')}} Initial definition.

Browser compatibility

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome(40.0)}} {{CompatGeckoDesktop(44)}}[1] {{CompatNo}} {{CompatUnknown}} {{CompatNo}}
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile(44)}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatChrome(40.0)}}

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

See also