An Introduction To Service Workers For Beginners
You might be hearing this buzzword — “Progressive Web Apps” for quite a while for now. Well, it’s nothing fancy, just a few
enhancements to web apps and a very sound selling term minted by Google (or Microsoft 🤷♂️). Twitter, Facebook, Flipkart, etc. all have a PWA for mobile devices. PWA enables the user to get a native-like experience on the browser, and the main driving force that powers a PWA is the Service Worker.
A Service Worker is a type of web worker, so let’s first understand web workers in the context of web technology.
A Service Worker is similar to a traditional web worker. It does not have access to DOM or the global window object but can intercept network requests and run as a programmable proxy between the web page and the server.
The Service Worker can leverage the Cache API and provide offline support. It can also be used for background syncs and push notifications.
Offline first is the need of the hour in this age of 4G/3G data connection on smartphones. Mobile data connections are highly unstable and slow and may affect the overall user experience. No one likes to see the dinosaur when the internet is down (it’s 2019 Google, please at least consider changing the game 🤦♂️). Don’t worry, with the help of service workers you can have a custom offline page for your app 🕺🎉.
Offline capability is a key characteristic of modern Progressive Web Applications. Offline first thinking must learn from and further what we’ve seen work with Responsive and Mobile First thinking.
The app.js file will register the sw.js file as a service worker. The browser then fires the install event in the background. After the installation, the activate event is fired, where the service worker becomes active and following that, it can listen to events like fetch and message.
For brevity purposes, I’m not going to go into much details of the lifecycle events.
But if you want to know more, you can visit this Web Fundamentals page.
That’s all for this story, just keeping it short and simple for you to understand. In the next story we’ll create a PWA using the App Shell Model.
Cheers and Happy Coding 🍻