Skip to content

HTML App Cache

Offline Web Applications with Service Workers (Replacing AppCache)

Section titled “Offline Web Applications with Service Workers (Replacing AppCache)”

Service workers provide a modern way to enable offline experiences for web applications, replacing the deprecated Application Cache.

A service worker is a script that your browser runs in the background, separate from a web page, enabling features that don’t need a web page or user interaction.

Key features include:

  • Offline capability: Intercepting network requests and serving cached responses when offline.
  • Background sync: Deferring actions until the user has stable connectivity.
  • Push notifications: Sending notifications to users even when the app isn’t open.
  • Improved performance: Proactively caching assets to speed up load times.
Note: Application Cache (AppCache), described in earlier versions of HTML5, is now deprecated and should not be used. Service Workers are the recommended technology for offline capabilities.

Service Workers are supported by all major modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. Internet Explorer does not support Service Workers.

Service workers act as a proxy server between the web app, the browser, and the network. They intercept network requests and can decide how to respond – serving from a cache, fetching from the network, or constructing a custom response.

A typical offline setup involves:

  1. Registering the Service Worker: Your main JavaScript file tells the browser to register a service worker script.
  2. Installation: The first time the service worker runs, an install event fires. This is where you typically cache essential assets (HTML, CSS, JS, images).
  3. Activation: After installation, the service worker activates, taking control of pages within its scope.
  4. Fetch Event Handling: When the browser requests a resource (e.g., an image, CSS file, or even a page navigation), the service worker’s fetch event listener intercepts it. The listener can check if the resource is in the cache and serve it directly if offline, or attempt to fetch it from the network otherwise.

Conceptual Example: Registering a Service Worker

Section titled “Conceptual Example: Registering a Service Worker”

In your main application JavaScript:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(error => {
console.log('Service Worker registration failed:', error);
});
}

Conceptual Example: Basic Caching in sw.js (Service Worker Script)

Section titled “Conceptual Example: Basic Caching in sw.js (Service Worker Script)”
const CACHE_NAME = 'my-app-cache-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/scripts/main.js',
'/images/logo.png'
];
self.addEventListener('install', event => {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Cache hit - return response
if (response) {
return response;
}
// Not in cache - fetch from network
return fetch(event.request);
}
)
);
});
This is a simplified example. Real-world service workers often involve more complex caching strategies, cache versioning, and update handling. For detailed guides, refer to resources like MDN Web Docs or web.dev.

Updating cached assets with service workers involves:

  • Updating the service worker script: Even a small change (like a comment) triggers the browser’s update process.
  • Creating a new cache: Typically, during the install event of the new service worker, you create a new cache (e.g., my-app-cache-v2) and populate it.
  • Cleaning up old caches: In the activate event of the new service worker, you remove outdated caches.

This ensures that users get the latest assets once the new service worker activates.