HTML Application Cache (Deprecated → Use Service Workers Instead)
Earlier, Application Cache (AppCache) was introduced in HTML5 to allow offline web applications. Developers could create a manifest file listing all the resources (HTML, CSS, JS, images) that should be cached by the browser for offline use.
Why Application Cache was Introduced
- To allow offline browsing.
- To improve page load speed.
- To reduce server requests.
Problems with Application Cache
Even though it was useful, developers faced many issues:
- Hard to update: Once cached, files didn’t update easily.
- Inflexible: No fine-grained control over caching strategy.
- Buggy behavior: Sometimes it cached unwanted files.
- Security risks: Limited control made it less secure.
👉 Because of these issues, AppCache was officially deprecated and removed from modern browsers.Service Workers: The Modern Solution
Now, we use Service Workers + Cache API for offline support.
A Service Worker is a script that runs in the background, separate from the web page. It can:
- Cache files for offline use.
- Handle network requests.
- Enable background sync.
- Show push notifications.
Benefits of Service Workers Over AppCache
- Full control over caching strategies.
- Offline browsing support.
- Faster performance with cached resources.
- Background sync (update data when internet comes back).
- Push notifications for real-time updates.
Example: Registering a Service Worker
Step 1: Register Service Worker in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Service Worker Example</title>
</head>
<body>
<h2>Offline Example with Service Worker</h2>
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("sw.js")
.then(() => console.log("Service Worker Registered ✅"))
.catch(err => console.log("SW Registration Failed ❌", err));
}
</script>
</body>
</html>
Step 2: Service Worker File (sw.js
)
const CACHE_NAME = "v1";
const urlsToCache = [
"/",
"/index.html",
"/style.css",
"/script.js"
];
// Install Service Worker and Cache Files
self.addEventListener("install", event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(urlsToCache);
})
);
});
// Fetch Cached Files When Offline
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
Real-World Use Cases of Service Workers
- News Websites → Read articles offline.
- E-commerce Stores → View cart and cached products offline.
- Progressive Web Apps (PWAs) → Installable apps with offline support.