put()
方法在
缓存
interface allows key/value pairs to be added to the current
缓存
对象。
Often, you will just want to
fetch()
one or more requests, then add the result straight to your cache. In such cases you are better off using
Cache.add()
/
Cache.addAll()
, as they are shorthand functions for one or more of these operations.
fetch(url).then(function(response) {
if (!response.ok) {
throw new TypeError('Bad response status');
}
return cache.put(url, response);
})
注意
:
put()
will overwrite any key/value pair previously stored in the cache that matches the request.
注意
:
Cache.add
/
Cache.addAll
do not cache responses with
Response.status
values that are not in the 200 range, whereas
Cache.put
lets you store any request/response pair. As a result,
Cache.add
/
Cache.addAll
can't be used to store opaque responses, whereas
Cache.put
can.
cache.put(request, response).then(function() {
// request/response pair has been added to the cache
});
Request
object or URL that you want to add to the cache.
响应
you want to match up to the request.
A
Promise
that resolves with
undefined
.
注意
: The promise will reject with a
TypeError
if the URL scheme is not
http
or
https
.
This example is from the MDN
sw-test example
(见
sw-test running live
). Here we wait for a
FetchEvent
to fire. We construct a custom response like so:
CacheStorage
使用
CacheStorage.match()
. If so, serve that.
v1
cache using
open()
, put the default network request in the cache using
Cache.put()
and return a clone of the default network request using
return response.clone()
. Clone is needed because
put()
consumes the response body.
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');
});
| 规范 | 状态 | 注释 |
|---|---|---|
|
服务工作者
The definition of 'Cache: put' in that specification. |
工作草案 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
put
|
Chrome
43
|
Edge 16 |
Firefox
39
|
IE No |
Opera
30
|
Safari 11 |
WebView Android
43
|
Chrome Android
43
|
Firefox Android 39 |
Opera Android
30
|
Safari iOS 11 |
Samsung Internet Android
4.0
|
完整支持
不支持
实验。期望将来行为有所改变。
见实现注意事项。
缓存
CacheStorage
Client
Clients
ExtendableEvent
FetchEvent
InstallEvent
Navigator.serviceWorker
NotificationEvent
PeriodicSyncEvent
PeriodicSyncManager
PeriodicSyncRegistration
ServiceWorker
ServiceWorkerContainer
ServiceWorkerGlobalScope
ServiceWorkerRegistration
SyncEvent
SyncManager
SyncRegistration
WindowClient