MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Cache API & Service Worker Storage0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
7.1IndexedDB Architecture & Transactions7.2Storing Complex Objects & Blobs in IndexedDB7.3Cache API & Service Worker Storage7.4Storage Quotas & Persistence Policies
HomeTutorialsJavaScript for AdvancedCache API & Service Worker Storage
Storage Quotas & Persistence Policies

Cache API & Service Worker Storage

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

In Progressive Web Applications (PWAs) and offline-capable web systems, network requests cannot be left to standard HTTP browser caching alone. The Cache API (caches) provides a programmatic storage mechanism for Request and Response object pairs, controlled directly by JavaScript and Service Workers.


1. What is the Cache API?

The Cache interface provides a persistent, asynchronous key-value store where:

  • Keys are HTTP Request objects (or URL strings).
  • Values are HTTP Response objects.
1 Browser Fetch Request
2 │
3 ▼
4 Service Worker Intercepts
5 │
6 ┌─────┴────────────────┐
7 ▼ ▼
8Cache API (caches.match) Live Network (fetch)
9(Offline Instant Return) (Slow / Online Only)

2. Core API Operations

1const CACHE_NAME = 'app-shell-v2';
2 
3// 1. Open or create a cache bucket
4const cache = await caches.open(CACHE_NAME);
5 
6// 2. Add resources (Fetches and stores automatically)
7await cache.addAll([
8 '/',
9 '/index.html',
10 '/styles/main.css',
11 '/scripts/app.js',
12 '/images/logo.svg'
13]);
14 
15// 3. Match resource from cache
16const cachedResponse = await cache.match('/styles/main.css');
17if (cachedResponse) {
18 console.log('Serving from Cache API:', cachedResponse.status);
19}
20 
21// 4. Delete obsolete cache buckets during Service Worker activate
22const keys = await caches.keys();
23await Promise.all(
24 keys
25 .filter(key => key !== CACHE_NAME)
26 .map(oldKey => caches.delete(oldKey))
27);

3. Top Caching Strategies

1. Cache First (Offline-First / Assets)

Ideal for static fonts, images, and immutable versioned JS bundles. Check cache first; only hit network if absent.

1async function cacheFirst(request) {
2 const cached = await caches.match(request);
3 if (cached) return cached;
4 const fresh = await fetch(request);
5 const cache = await caches.open(CACHE_NAME);
6 cache.put(request, fresh.clone()); // Clone before caching!
7 return fresh;
8}

2. Network First (Dynamic Data)

Ideal for account balances or live inventory. Try network; fallback to cache if offline.

1async function networkFirst(request) {
2 try {
3 const networkResponse = await fetch(request);
4 const cache = await caches.open(CACHE_NAME);
5 cache.put(request, networkResponse.clone());
6 return networkResponse;
7 } catch (error) {
8 const cached = await caches.match(request);
9 if (cached) return cached;
10 throw error;
11 }
12}

3. Stale-While-Revalidate (Fastest & Fresh)

Return cached response immediately (instant load), while asynchronously fetching the network in the background to update the cache for next time!


4. The Critical Gotcha: Cloning Responses

A Response body stream can only be read once! If you store a response in the Cache API and return it to the browser, you must clone it first:

1// DANGER: Fails without cloning!
2// cache.put(request, response);
3// return response; // TypeError: response body stream already read!
4 
5// CORRECT PATTERN:
6cache.put(request, response.clone());
7return response;

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What types of objects are paired as keys and values inside the Cache API?
Question 2
Why must a Response object be cloned (response.clone()) before being stored in cache.put()?
Question 3
Which caching strategy returns cached assets immediately for instant speed while silently updating the cache in the background?
Question 4
In which Service Worker lifecycle event are outdated cache buckets typically purged?
Question 5
Can the Cache API be accessed from the main window thread or only inside Service Workers?
Next Lesson

Storage Quotas & Persistence Policies

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Storing Complex Objects & Blobs in IndexedDBStorage Quotas & Persistence Policies

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext