DIV CSS 佈局教程網

JavaScript 中 caches(CacheStorage)使用詳解
編輯:JavaScript基礎知識     

localStorage 家喻戶曉,但本地存儲家族遠不止它。除了之前聊過的 sessionStorage,還有一個神奇的 CacheStorage——它專門用來存儲 Response 對象,即對 HTTP 響應做緩存。localStorage 雖也能勝任,但 CacheStorage 顯然更專業。

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。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved