CacheStorage
interface represents the storage for
缓存
对象。
接口:
ServiceWorker
or other type of worker or
window
scope (you’re not limited to only using it with service workers, even though the
服务工作者
spec defines it).
注意
:
Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS
.
window.caches
will be undefined unless an SSL certificate is configured.
缓存
对象。
使用
CacheStorage.open()
to obtain a
缓存
实例。
使用
CacheStorage.match()
to check if a given
Request
is a key in any of the
缓存
objects that the
CacheStorage
object tracks.
You can access
CacheStorage
through the global
caches
特性。
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.
注意
:
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()
.
CacheStorage.match()
Request
is a key in any of the
缓存
objects that the
CacheStorage
object tracks, and returns a
Promise
that resolves to that match.
CacheStorage.has()
Promise
that resolves to
true
若
缓存
object matching the
cacheName
exists.
CacheStorage.open()
Promise
that resolves to the
缓存
object matching the
cacheName
(a new cache is created if it doesn't already exist.)
CacheStorage.delete()
缓存
object matching the
cacheName
, and if found, deletes the
缓存
object and returns a
Promise
that resolves to
true
. If no
缓存
object is found, it resolves to
false
.
CacheStorage.keys()
Promise
that will resolve with an array containing strings corresponding to all of the named
缓存
objects tracked by the
CacheStorage
. Use this method to iterate over a list of all the
缓存
对象。
This code snippet is from the MDN
sw-test example
(见
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:
Cache.put
(
cache.put(event.request, response.clone())
)。
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 } );
}
| 规范 | 状态 | 注释 |
|---|---|---|
|
服务工作者
The definition of 'CacheStorage' in that specification. |
工作草案 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CacheStorage
|
Chrome
40
|
Edge ≤18 |
Firefox
44
|
IE No | Opera 27 | Safari 11.1 |
WebView Android
40
|
Chrome Android
40
|
Firefox Android 44 | Opera Android 27 | Safari iOS 11.3 |
Samsung Internet Android
4.0
|
delete
|
Chrome 40 | Edge 16 |
Firefox
44
|
IE No | Opera 27 | Safari 11.1 | WebView Android 40 | Chrome Android 40 | Firefox Android 44 | Opera Android 27 | Safari iOS Yes | Samsung Internet Android 4.0 |
has
|
Chrome 40 | Edge 16 |
Firefox
44
|
IE No | Opera 27 | Safari 11.1 | WebView Android 40 | Chrome Android 40 | Firefox Android 44 | Opera Android 27 | Safari iOS Yes | Samsung Internet Android 4.0 |
keys
|
Chrome 40 | Edge 16 |
Firefox
44
|
IE No | Opera 27 | Safari 11.1 | WebView Android 40 | Chrome Android 40 | Firefox Android 44 | Opera Android 27 | Safari iOS Yes | Samsung Internet Android 4.0 |
match
|
Chrome
54
|
Edge 16 |
Firefox
44
|
IE No |
Opera
41
|
Safari 11.1 |
WebView Android
54
|
Chrome Android
54
|
Firefox Android 44 |
Opera Android
41
|
Safari iOS Yes |
Samsung Internet Android
6.0
|
open
|
Chrome 40 | Edge 16 |
Firefox
44
|
IE No | Opera 27 | Safari 11.1 | WebView Android 40 | Chrome Android 40 | Firefox Android 44 | Opera Android 27 | Safari iOS Yes | Samsung Internet Android 4.0 |
| Secure context required | Chrome 65 | Edge ≤79 | Firefox 44 | IE No | Opera 52 | Safari Yes | WebView Android 65 | Chrome Android 65 | Firefox Android 44 | Opera Android 47 | Safari iOS Yes | Samsung Internet Android 9.0 |
完整支持
不支持
实验。期望将来行为有所改变。
见实现注意事项。
CacheStorage
缓存
Client
Clients
ExtendableEvent
FetchEvent
InstallEvent
Navigator.serviceWorker
NotificationEvent
PeriodicSyncEvent
PeriodicSyncManager
PeriodicSyncRegistration
ServiceWorker
ServiceWorkerContainer
ServiceWorkerGlobalScope
ServiceWorkerRegistration
SyncEvent
SyncManager
SyncRegistration
WindowClient