The Hidden Hero of Modern Web: Service Worker
It works even without internet, sends instant notifications, and empowers web applications - the invisible helper in the browser's background.
🚀 Core Capabilities
Service Workers bring powerful features to the web, previously exclusive to native applications:
📡 Offline Capability
Enables users to access content even when the internet is down.
⚡ Fast Performance
Speeds up page transitions by loading from the cache instantly.
🔔 Instant Notifications
Sends notifications even when the browser is closed, increasing user engagement.
🔄 Background Synchronization
Saves actions when the connection is lost and sends them to the server when it's restored.
🔄 Life Cycle
Its behavior is managed by three main stages. Understanding this cycle is key to using it correctly.
1. Registration (Registration)
Initiates the process and informs the browser of the service worker file's location.
2. Installation (Installation)
Caches assets and prepares necessary files for the application to work.
3. Activation (Activation)
Cleans up old caches and takes full control to start working.
💻 Code Examples
📦 Caching Assets
We use the `install` event to cache the application's core files (App Shell) for offline access.
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll([
'/index.html',
'/style.css',
'/app.js'
]);
})
);
});
🌐 Managing Network Requests
We catch network requests with the `fetch` event. First, we check the cache; if the resource is not found, we go to the network.
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});