cache API是一個很強大的API,它可以在window環境和serviceWorker環境使用,配合serviceWorker可以讓我們自己來管理緩存。
caches
caches是一個全局接口,可以在window和worker下訪問到。我們可以使用caches.open
來獲取(如果沒有的話會創建)一個cache對象:
caches.open('test').then(cache => console.log(cache));
此外, caches還有以下API:
caches.has('test') // 有沒有cacheName爲test的cache
caches.delete('test') // 刪除一個cache對象
caches.match('https;//www.baidu.com') //找到一個url對應的cache 響應
caches.match('https;//www.baidu.com', {cacheName:'test'}) //在指定的cacheName下找到一個url對應的cache 響應
需要注意的是,上面的API都返回一個promise
cache對象
如果把caches理解成數據庫,那麼cache對象就像一張表,關聯了request 和 response, cache對象有以下方法:
cache.add, cache.addAll
這兩個方法都可以把一些請求緩存下來,區別在於addAll可以接受多個請求或者url。常用於提前緩存一些靜態資源。
cache.add('https://www.baidu.com?a=1');
// serviceWorker
addEventListener('install', event => {
const preCache = async () => {
const cache = await caches.open('static-v1');
return cache.addAll([
'/',
'/about/',
'/static/styles.css'
]);
};
event.waitUntil(preCache());
});
cache.put
cache.put 接受兩個參數,一個request, 一個response,這讓我們可以更新緩存或者僞造響應。
caches.open('test').then((cache) => {
cache.put('/hello', new Response('hello word', {status: 200}))
} )
cache.match
與caches.match用法一樣,匹配一個request對應的response,如果沒有,則返回undefined
caches.open('test').then((cache) => {
cache.match('/hello').then(res => res?.text()).then(console.log)
} )
cache.delete
刪除一個緩存,成功返回true,失敗返回false
caches.open('test').then((cache) => {
cache.delete('/hello').then(console.log)
} )
總結
上面就是cache API的內容了,當它可以service Worker一起使用的時候,可以發揮出巨大的威力