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
หัวข้อที่มีชื่อว่า “Cache API”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
Storage Manager
หัวข้อที่มีชื่อว่า “Storage Manager”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 และ Storage Manager |
cache-api | method ทั้งหมดของ Cache API: open, put, add, addAll, match, delete, keys |
storage-manager | estimate(), persist(), และ persisted() อย่างละเอียด |
eviction-and-persistence | Best-effort vs persistent storage และเมื่อใดที่ browser จะลบข้อมูล |
cache-vs-indexeddb | คู่มือการตัดสินใจ: Cache API vs IndexedDB vs localStorage |