[WebAPIs] Cache API
keywords: Cache API
Cache API 可以用來幫助我們儲存 Request-Response 這種對應關係的資料:
caches是存在window的全域物件,用來建立和刪除 Cache Storage 物件。cache則是從 Cache Storage 中拿出的許多 request-response 對應的項目。
🔖 Using the Cache API @ Google Developers > Web Fundamentals 🔖 Cache API 101 @ bitsofco
建立 Cache 並添加項目(CREATE)
keywords: caches.open(<cache-name>), cache.add(<request>), cache.addAll([<req1>, <req2>])
要建立或存取 cache 物件時需要使用 caches.open(<cache-name>):
caches.open('my-cache').then((myCache) => {
// Do stuff with myCache
});
若要在 cache 物件中添加 request-response 的象物,可以使用 cache.add(<request>) 方法,add() 裡面要放 request object 或者單純一個 URL。
caches.open('my-cache').then((myCache) => {
// URL only
myCache.add('/subscribe');
// Full request object
myCache.add(
new Request('/subscribe', {
method: 'GET',
headers: new Headers({
'Content-Type': 'text/html',
}),
/* more request options */
}),
);
});
瀏覽器會根據所給的 Request 發送 Fetch 請求,並且把 response 儲存在瀏覽器的 cache 物件中。
如果想要一次添加許多的項目,可以使用 addAll() 這個方法,它可以接受帶有 requests 的陣列:
caches.open('my-cache').then((myCache) => {
myCache.addAll(['/subscribe', '/assets/images/profile.png']);
});