Cache:put() 方法
注意:此功能在 Web Workers 中可用。
Cache 介面的 put() 方法允許將鍵/值對新增到當前的 Cache 物件。
通常,您只想 fetch() 一個或多個請求,然後將結果直接新增到您的快取中。在這種情況下,您最好使用 Cache.add()/Cache.addAll(),因為它們是一個或多個這些操作的簡寫函式。
js
fetch(url).then((response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
注意:put() 會覆蓋快取中先前儲存的與請求匹配的任何鍵/值對。
注意: Cache.add/Cache.addAll 不會快取 Response.status 值不在 200 範圍內的響應,而 Cache.put 允許您儲存任何請求/響應對。因此,Cache.add/Cache.addAll 不能用於儲存不透明響應,而 Cache.put 可以。
語法
js
put(request, response)
引數
返回值
一個 Promise,解析為 undefined。
異常
TypeError-
如果 URL 方案不是
http或https,則返回此值。
示例
此示例來自 MDN 的 simple-service-worker 示例(請參閱 正在執行的 simple-service-worker 即時示例)。在這裡,我們等待 FetchEvent 觸發。我們像這樣構造一個自定義響應:
- 使用
CacheStorage.match()檢查是否在CacheStorage中找到請求的匹配項。如果找到,則提供該匹配項。 - 如果沒有找到,則使用
open()開啟v1快取,使用Cache.put()將預設網路請求放入快取,並使用return response.clone()返回預設網路請求的克隆。需要克隆,因為put()會消耗響應體。 - 如果失敗(例如,因為網路中斷),則返回一個備用響應。
js
let response;
const cachedResponse = caches
.match(event.request)
.then((r) => (r !== undefined ? r : fetch(event.request)))
.then((r) => {
response = r;
caches.open("v1").then((cache) => cache.put(event.request, response));
return response.clone();
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));
規範
| 規範 |
|---|
| Service Workers # cache-put |
瀏覽器相容性
載入中…