loading...

Explain how service workers work like I'm five

lauragift21 profile image Gift Egwuenu ・1 min read

I have been hearing about offline first for a while now but still not gotten my head wrapped around Service workers and how they function. Anyone care to explain how it works?

Discussion

markdown guide
 

Imagine that your browser is it's own planet in space and wants to talk other planets in the galaxy. The way 'planets' talk to each other is via a giant space pipe (HTTP protocol). Sometimes that giant pipe is not around so you can't talk with other planets (offline).

This where Service Workers can come in. Service Workers are like alien spaceships that can sit between the space pipe and your planet. When the service worker is around everything goes through it first, and it can remember what came through the pipe.

For example, there is a service worker around but no space pipe(offline) and you ask for the cat gif that you saw yesterday, the service worker can give you that cat gif without the space pipe(network) because it remembers it (service worker cache).

Check the source for an even better explanation.

Service Worker as alien spaceships

Source: Service Worker, what are you ? by @kosamari

 

Ooooh boy. This is a challenge. But I'll try.

Service Workers are like little Node.js servers that the browser spins up on-demand. Instead of sending HTTP requests directly to the network, it sends the requests to a JavaScript process that decides what to do with them. The simplest Service Worker acts like a reverse proxy server (aka load balancer). It receives an HTTP request, says "nope, you handle it" and returns the request back to the browser. The next simplest Service Worker is a proxy that simply takes incoming requests, uses fetch(event.request.url) to fetch the response, then does something with that response before passing it back to the browser, which then passes it back to your webpage.

The programming API is very similar to the raw 'http' library in Node, or a "serverless" or "cloud lambda function" API. Here's a quick comparison:

// Node.js
require('http').createServer((request, response) => {
  response.statusCode = 200;
  response.setHeader('Content-Type', 'text/plain');
  response.write("Hello world!", 'utf8');
  response.end();
});
// Service Worker
self.addEventListener('fetch', event =>
  event.respondWith(
    new Response("Hello world!", {
      status: 200,
      headers: {
        'Content-Type': 'text/plain'
      }
    })
  )
);

Okay... so they're not terribly similar in terms of actual syntax. But operationally they are doing nearly the same thing. They respond to every HTTP request with "Hello world!".

Once you realize that a Service Worker is really just a little server running on your client's computer, it's obvious all the crazy things you can do with it. The simplest is to cache results so that your webapp works offline. But you can do all sorts of things, such as redirect requests, modify requests, modify responses. You can make a service worker that transpiles JavaScript using Babel or even modify ExpressJS so you can do server-side template rendering. You can intercept HTTP requests and retrieve the files using Bittorrent.

One thing you can't do though is assume that it is running all the time. It's not. In fact, as soon as you close all the webpages using it, the browser will kill the Service Worker thread. So you can't store state in memory. You have to assume that any moment could be it's last. Maybe it's running on a smartphone, and as soon as the user switches apps or turns of the screen, the browser will kill it to save battery life.

This is a bummer. Because one of the best things about having a server, is you can send stuff to it remotely! Service workers don't have an IP address though. The user's browser can communicate with it, and it can initiate a communication to another server, but how could another server contact your service worker if your service worker isn't always running?

This is where the browser vendors and mobile OS's came up with a great hack. Your service worker can't always be running - that would be terrible for battery life. But their servers - Google's and Apple's - are always running. And the phone's OS is always in contact with those servers (yay privacy's dead!). And the phone's OS can open the phone's web browser. So like the world's geekiest relay, these all coordinate so that you (the website admin) can send a message to an individual service worker running on someone's phone, by sending the message to Google (or Apple's) "push" server, which sends the message to the phone's OS, which shows a notification, which when users click on it opens their browser to your webpage at which point the browser "spins up" your little Service Worker service who receives the "push" event. Since each user has their own Service Worker, you can individualize each push message to be just for them. (Usually by associating their Service Worker with an account on your website.) That way users can choose their own personal notification preferences. Crazy right?!

 

You hail a taxi, get in the car, they take you to your destination, you might make small talk along the way, you get going and you pay. That's a bit like visiting a webpage.

You hail a taxi, they give you their card about the limo service they provide, which also does pickup and delivery of your dry cleaning. You're intrigued about the possibility of getting texts about the status of your ride and other things like that. That's a service worker. You and the driver are going to exchange info so the relationship can become more than just the single ride.

Service workers give you access to secondary browser APIs which allow you to do things like storing an offline page, caching pages for offline browsing, and the ability to send push notifications to the user, and basically do things outside the typical lifecycle of a webpage visit. This is a browser behavior, but it sort of seems like a system-level behavior, because it sort of is. The line is blurred with the increased power of the browser.

One thing that is a bit confusing is that right now service workers do a handful of neat tricks, but service workers will find new use cases in their existing functionality and in future features that are implemented to go along with the current set of features. That's why it's not just referred to as "a slightly different caching api and ability to send push notifications", it's going to become more powerful through discovery and growth, just as the browser has.

You might also be thinking of the above example and be thinking "In a way, you're describing Uber or Lyft already", and that sort of makes sense. The things that service workers can do are sort of an effort to bring the power of native APIs to the web. The benefits of the web are great, but it sometimes loses out to native for reasons it doesn't need to. Service workers close some of those gaps. You still don't get all the native APIs, but who knows what the future holds?

In practice, service workers let you load a JavaScript file that configures what it can do. It's just code like any other JavaScript file, but instead of giving you access to things like document and window and events like onclick, you gets like install, activate to listen to and then go to work with.

If you're interested in adding basic service worker functionality to a project, I'd start with following the instructions, pasting some of the boilerplate in, and working simply with creating an "offline" page. I think that's the base case, and that's how I started.

 
 

Great explanation! Thanks for this 🙌🏾

 

Thanks. Best explanation I've gotten btw I think dev.to offline page is the best 😄

 

Think browser as a shop owner .

Whenever you request items , he will buy it from the maker and give it to you .

But in some cases what if the manufacturer is not available ?(Internet Down)

That's why the manufacturer will say "Hey Buddy ! I will give you some basics that every customer want But alert me for any specific order "

So that time , when you ask for a product the shopkeeper delivers it from his warehouse . But you won't know the difference where it came from

He'll deliver as long as available .

So The manufacturer is the server like google,amazon etc...

The shop keeper is your browser

The site which says save some very basic content like start page , end page etc mentioned in a page called service worker

Simply service worker is a manual from the server to the browser to which assets to download and what to do when a specific url is request(irrespective of your internet connection)

Try 2048

Its also a Progressive web app with service workers implemented and works offline when you go to that url

 

How often are users "offline"? Because so far the only useful use cases I see for Services Worker is offline uses for WebApp. Sort of like Turbolinks with Services Worker to replace the current App Shell Rails has.