Make your web app load faster and work offline by caching files directly in the browser, no fancy setup needed.

Introduction
If you’ve ever opened a website offline and it still loaded, congratulations, you’ve experienced a Service Worker in action.
It’s not magic. It’s just a tiny JavaScript file running in the background that:
- Caches your app files (HTML, CSS, JS, images)
- Serves them instantly next time
- Works even without the internet
And the best part? You can build one yourself in less than 30 lines of code.
In this guide, we’ll walk through how to create a basic Service Worker that caches your app’s assets step by step.
1️. What Is a Service Worker?
A Service Worker is a script that runs in the background, separate from your web page.
It can:
- Intercept network requests
- Cache resources
- Deliver offline experiences
- Enable background sync and push notifications
Think of it like a proxy between your app and the network, but one you control.
2️. How Service Workers Work (The Lifecycle)
Every Service Worker goes through 3 stages:
- Install → Cache your files
- Activate → Clean up old caches
- Fetch → Serve cached content when offline
Let’s see how to build each part.
3️. Step 1: Register the Service Worker
In your main JavaScript file (e.g., app.js or index.js):
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then(() => console.log("✅ Service Worker registered"))
.catch((err) => console.error("SW registration failed:", err));
}
✅ This tells the browser to look for a file called sw.js (the Service Worker).
✅ Once registered, it runs in the background even when you close the page.
4️. Step 2: Create the Service Worker File (sw.js)
Inside your project’s root folder, create a file named. sw.js.
Add this basic setup:
const CACHE_NAME = "v1";
const ASSETS = [
"/", // index.html
"/index.html",
"/styles.css",
"/app.js",
"/logo.png",
];
This defines which files you want to cache.
You can add any assets your app needs offline (HTML, JS, CSS, images, fonts, etc.).
5️. Step 3: Cache Files During Installation
Add an install event that pre-caches your assets:
self.addEventListener("install", (event) => {
console.log("Service Worker: Installing…");
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Service Worker: Caching files");
return cache.addAll(ASSETS);
})
);
});
✅ Runs once when the Service Worker is first installed
✅ Adds all files to the browser’s Cache API
6️. Step 4: Serve Cached Files on Fetch
Now we intercept all network requests and serve cached ones first:
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
// Serve from cache if available
if (cachedResponse) {
console.log("Serving from cache:", event.request.url);
return cachedResponse;
}
// Otherwise, fetch from network
return fetch(event.request);
})
);
});
✅ If offline → serves from cache
✅ If online → fetches fresh data
This makes your app offline-capable instantly.
7️. Step 5: Clear Old Cache on Activation
When you update your app, old caches should be removed:
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => {
console.log("Deleting old cache:", key);
return caches.delete(key);
})
)
)
);
});
✅ Keeps cache clean
✅ Ensures users always get the latest version
8️. Test It Out
- Run your app in Chrome
- Open DevTools → Application → Service Workers
- Check “Offline” in the Network tab
- Reload your app
💥 Your app should still load even without internet!
9️. Optional: Add a “Network-First” Strategy
If you want your app to try the network first (and fall back to cache only when offline):
self.addEventListener("fetch", (event) => {
event.respondWith(
fetch(event.request)
.then((res) => {
const resClone = res.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, resClone));
return res;
})
.catch(() => caches.match(event.request))
);
});
✅ Perfect for dynamic APIs or frequently updated data.
10. Quick Recap

Why This Matters
Service Workers + Cache API give you:
✅ Instant load times after first visit
✅ Offline-ready experiences
✅ Lower network costs
✅ Better Lighthouse scores
It’s the foundation of every Progressive Web App and it takes less than 50 lines of code.
Conclusion
You don’t need complex frameworks to make your app offline-ready.
A simple Service Worker with a few lines of caching logic can make your site feel like a native app, fast, reliable, and always available.
✅ In short:
- Register your Service Worker
- Cache your files
- Serve from cache when offline
Once you do that, your app won’t just work, it’ll feel instant.
Call to Action
Have you tried adding a Service Worker to your project yet?
Drop your results (or your first caching bug!) in the comments 👇
And if your teammate still thinks offline support needs “special hosting,” send them this post and let the Cache API prove them wrong.


Leave a Reply