localStorage 應該家喻戶曉,但本地存儲這個家族遠不止它。之前聊過 sessionStorage,現在還有個神奇的 CacheStorage——它用來存儲 Response 對象,也就是對 HTTP 響應做緩存。雖然 localStorage 也能做,但它可能更專業。
CacheStorage 在瀏覽器上的引用名叫 caches 而非駝峰寫法的 cacheStorage,它定義在 ServiceWorker 規範中。CacheStorage 是多個 Cache 的集合,而每個 Cache 可以存儲多個 Response 對象。
廢話不多說,下面是 demo:
<script> caches.delete('c1'); caches.delete('c2'); Promise.all([ caches.open('c1').then(function(cache) { return cache.put('/hehe', new Response('aaa', { status: 200 })); }), caches.open('c2').then(function(cache) { return cache.put('/hehe', new Response('bbb', { status: 200 })); }) ]).then(function() { return caches.match('/hehe'); }).then(function(response) { return response.text(); }).then(function(body) { console.log(body); }); </script>
首先,在 caches 上調用 open 方法就能異步得到一個 Cache 對象的引用。在這個對象上,我們可以把 Response 對象 put 進去(參數是一個 URL 和一個 Response 對象),用 match 方法取出(傳入 URL 取出對應的 Response 對象)。
match 方法不僅能在 Cache 上調用,CacheStorage 上也有 match 方法。比如上面例子打開了兩個 Cache,都寫入一個叫 /hehe 的 URL,寫入完成後到外部 CacheStorage 上調 match 匹配 /hehe,結果是隨機的(沒找到這個規則在哪裡定義)。
雖然例子只對 Cache put 了一個數據,但 Cache 本身可存放更多 URL/Response 對,並提供了 delete(刪除)、keys(遍歷)等方法。不過 Cache 不像 localStorage 那樣有 clear 方法,若非清空一個 Cache,可直接在 CacheStorage 上把整個 Cache delete 掉再重新 open。
這套 API 和 ServiceWorker 同宗同源,通常用於 ServiceWorker 中,整個設計風格也和它一樣都基於 Promise。