ข้ามไปยังเนื้อหา

Cache API และ Storage Quota

โมดูลนี้ครอบคลุม browser API ที่เกี่ยวข้องกันสองตัว ได้แก่

  • Cache API — กลไกการจัดเก็บข้อมูลสำหรับคู่ Request/Response ออกแบบมาเพื่อแคช HTTP response และ static asset โดยเฉพาะ เพื่อให้สามารถให้บริการแบบออฟไลน์หรือโดยไม่ต้องเข้าถึงเครือข่าย
  • Storage Manager — อินเทอร์เฟซ navigator.storage ที่รายงานปริมาณพื้นที่ดิสก์ที่ origin ปัจจุบันใช้อยู่ และ quota ที่ได้รับอนุญาต นอกจากนี้ยังให้คุณร้องขอ persistent storage เพื่อป้องกันไม่ให้ browser ลบข้อมูลเมื่อดิสก์เต็ม

Cache API อยู่ภายใต้ global object caches คุณเปิด cache ที่มีชื่อ จัดเก็บคู่ Request/Response ลงไป แล้วดึงกลับมาในภายหลังโดยจับคู่กับ URL ของ request การใช้งานที่พบบ่อยที่สุดคือภายใน Service Worker ซึ่ง worker จะดักจับ network request และส่ง response จาก cache เมื่อไม่มีการเชื่อมต่อเครือข่าย

const cache = await caches.open('my-app-v1');
await cache.put('/api/data.json', new Response('{"ok":true}'));
const response = await cache.match('/api/data.json');
console.log(await response.text()); // {"ok":true}

Cache API ถูกใช้ร่วมกับ Service Workers เป็นหลักสำหรับกลยุทธ์ออฟไลน์และ PWA ดูรูปแบบการแคชด้วย Service Worker ได้ที่ PWA course

navigator.storage ให้ข้อมูล quota และการ eviction:

const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${usage} of ${quota} bytes`);
const isPersistent = await navigator.storage.persisted();
console.log('Persistent:', isPersistent);
flowchart LR
  Browser -->|caches.open / put / match| CacheAPI[Cache API
stores Request/Response pairs]
  CacheAPI -->|served by| SW[Service Workers]
  Browser -->|estimate / persist / persisted| SM[Storage Manager
usage · quota · eviction control]
Cache API เก็บคู่ Request/Response สำหรับ Service Workers; Storage Manager รายงาน usage และ quota
บทเรียนสิ่งที่จะได้เรียนรู้
หน้านี้ภาพรวมระดับสูงของ Cache API และ Storage Manager
cache-apimethod ทั้งหมดของ Cache API: open, put, add, addAll, match, delete, keys
storage-managerestimate(), persist(), และ persisted() อย่างละเอียด
eviction-and-persistenceBest-effort vs persistent storage และเมื่อใดที่ browser จะลบข้อมูล
cache-vs-indexeddbคู่มือการตัดสินใจ: Cache API vs IndexedDB vs localStorage
Browser Storage
Cache API จัดเก็บอะไร?
global object ใดเป็นจุดเข้าถึง Cache API?
navigator.storage.estimate() คืนค่าอะไร?