Cache API in JavaScript

Javascript Jeep🚙💨
JavaScript_Dots
Published in
3 min readMay 23, 2020

--

Learn how to cache resources with Cache API in JavaScript.

Cache API Cheat-sheet

The Cache API allows Service Workers to have a control over resources(HTML pages, CSS, JavaScript files, images, JSON, etc) to be cached. Through Cache API a Service Worker can cache resources for offline and retrieve them later.

Detecting the cache support

Check if the caches object available in window.

let isCacheSupported = 'caches' in window;

caches is an instance of CacheStorage .

Creating/Initialize Cache

We can create a cache with name using open method, which will returns a promise . If the cache already exists , then it don’t create a new cache.

caches.open('cacheName').then( cache => {});
  • You cannot you cannot access caches set up for others origin(domain).
  • The cache which you’r are creating will be created for your domain.
  • You can add multiple cache for same domain, which you can access by caches.keys()

Adding an item to cache

You can cache a resource using three methods add , addAll , set . add() and addAll() method automatically fetches a resource, and…

--

--