Clean • Professional
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.
Even though it was useful, developers faced many issues:
👉 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:
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);
})
);
});