An Introduction To Service Workers For Beginners

Photo by from Pexels

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.
Web workers serve as a background thread to the main UI thread or the web page and can run JavaScript code independently that may take a certain amount of time to execute without affecting the main UI thread. As we know, JavaScript is a single-threaded language, performing computation-heavy tasks on the main thread can remarkably affect the performance.For the benefit of performance, web workers can run such tasks.

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.

A Service Worker; when created goes through a lifecycle of its own. Let’s say we have an sw.js file which is a service worker inside of the root of the project (so that the service worker can control the entire project) and an app.js file which is the main javascript file that drives our app. 
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.

app.js (Main JavaScript File)
sw.js (Service Worker File)

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 🍻