Introduction to Service Workers for Newbies
- Abhishek Kumar
- 22 Mar, 2025
- 4 Mins read
Have you ever visited a website that works flawlessly even when you’re not connected to internet? (eg: demo website) The ability of certain web apps to update content or send you notifications without requiring a continuous internet connection may have surprised you. If you’ve ever been fascinated by the idea of building such a website You’re in the right place. The secret behind these capabilities lies in a powerful feature known as service workers.
In simple word a service worker is a script that runs in the background of a web page, separate from the main JavaScript thread. it enable us to create offline-capable web applications, manage push notifications, and significantly enhance web page performance by intercepting and handling network requests
Now we know what a service worker can do, let’s try to implement it in our webapp. but before implementing lets know something about service worker lifecycle
The Service Worker Lifecycle
The service worker lifecycle consists of three main stages:
-
Registration:
- This is the initial step where the browser registers the service worker script.
- It involves downloading the service worker file and preparing it for use.
-
Installation:
- During this stage, the service worker caches necessary assets.
- It prepares to handle requests by setting up the environment.
-
Activation:
- The service worker becomes active and takes control.
- It starts managing network requests and handling tasks like push notifications.
To register a service worker, we need to include a script in your html file Here’s a simple example:
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('sw.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
Note: Service worker registration only works over secure connections (HTTPS or localhost), and the service worker’s scope is limited to its registration scope.
that’s it, we’ve added service worker in our web app but you may following error
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:5500/') with script ('http://127.0.0.1:5500/sw.js'): A bad HTTP response code (404) was received when fetching the script.
lets write sw.js
to resolve this error. in our sw.js
file we will be caching our website so that user can browse our website even without internet.
Caching and Offline Support
Service workers can cache resources for offline access. Here’s how you can add items to the cache:
const CACHE_NAME = 'v1';
const urlsToCache = [
'/',
'*.html',
'*.css',
'/images/*.(png|jpg|jpeg|gif|svg|webp)'
];
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if(response) {
return response;
}
return fetch(event.request).then(fetchResponse => {
const responseClone = fetchResponse.clone();
if (shouldCache(event.request.url)) {
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, responseClone)
});
}
return fetchResponse;
});
})
);
});
function shouldCache(url) {
if (!url.startsWith('http')) {
return false;
}
return urlsToCache.some(pattern => {
const regexPattern = pattern.replace(/\*/g, '.*');
const regex = new RegExp(regexPattern);
return regex.test(url);
});
}
Great! Now our website can work offline. When users visit our website, the specified resources will be cached, allowing them to access the content even without an internet connection
Background Sync and Notifications
Service workers can handle background sync and push notifications, allowing your web application to stay up-to-date even when it’s not actively being used. This can greatly enhance the user experience by providing timely updates and notifications.
Pros and Cons of Service Workers
Pros: Improve performance by caching resources. Enable offline functionality for web applications. Handle push notifications even when the app is closed.
Cons: Only work in HTTPS environments. Require a separate JavaScript file, which can add overhead.
Best Practices
- Optimize Service Worker Size: Minimize the size of your service worker script to ensure quick download and installation. Use tools like minification and compression to reduce file size.
- Use Caching Strategies: Implement efficient caching strategies to reduce the number of requests and store information for future use.
- Versioning: Assign version numbers to your service worker script to ensure users access the latest version and can roll back if needed.
checkout service worker demo at https://abhishekjnvk.github.io/service-worker-demo/
Additional Resources
MDN Web Docs on Service Workers
Google Developers Guide to Service Workers
Now, go forth and conquer the web with your service worker knowledge! Happy coding 🚀🐆🍞
If you like this article, don't forget to share it with your friends and colleagues.