Lesson 92 – Registering a Service Worker in JavaScript
Service Workers are powerful tools that allow JavaScript to run in the background, independently of web pages, enabling features like offline capabilities, background syncs, and push notifications.
In this lesson, we'll focus on how to register a Service Worker in your web application.
What is a Service Worker?
A Service Worker is a special type of web worker that acts like a proxy between your web app and the network (or cache). It's designed to enable offline experiences, push notifications, and background data syncing.
But before you can use a service worker, you must register it from your main JavaScript thread.
How to Register a Service Worker
Here’s a simple step-by-step:
1. Check if the Browser Supports Service Workers
if ('serviceWorker' in navigator) {
// Service Worker supported
}
2. Register the Service Worker File
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
Explanation:
/sw.js
is the service worker script you’ll write..then()
runs when registration is successful..catch()
handles errors if registration fails.
Important Points
- Registration should be done on page load or soon after.
- The path matters! Service workers can only control pages that are under their scope.
- HTTPS is required! (Except for localhost during development.)
Example Folder Structure
/index.html
/app.js
/sw.js
index.html
? Your main pageapp.js
? Contains the registration codesw.js
? The service worker file itself
Quick Exercise
- Try writing a basic
sw.js
file containing:
self.addEventListener('install', function(event) {
console.log('Service Worker installing.');
});
self.addEventListener('activate', function(event) {
console.log('Service Worker activated.');
});
Then register it as shown above and check your browser’s console!
Summary
- Service Workers allow you to intercept network requests and cache files.
- Always check for browser support first.
- Use
navigator.serviceWorker.register()
to register your service worker.