The difference between Service Workers, Web Workers and WebSockets

As fairly-new web technologies, Service Workers, Web Workers and WebSockets all started, stalled, and then sort of made a resurgence. And so I find myself somewhat confused by exactly what each does, what the differences between them are, and what purpose each ideally serves.

I tried searching for some comparison articles, but was surprised by the lack of search results comparing all three of these technologies. I found two that come close…

  1. Getting Things Done with WebSockets and Web Workers is an online chapter from Learning HTML5 Game Programming.
  2. Ajax vs. Web sockets vs. Web Workers is a StackOverflow article.

…but neither compares the three I was curious about… So I decided to get to know them all a little better and document my findings here (so I could come back and remind myself again later…).

TL;DR

  • Service Worker:
    Background service that handles network requests. Ideal for dealing with offline situations and background syncs or push notifications. Cannot directly interact with the DOM. Communication must go through the Service Worker’s postMessage method.
  • Web Worker:
    Mimics multithreading, allowing intensive scripts to be run in the background so they do not block other scripts from running. Ideal for keeping your UI responsive while also performing processor-intensive functions. Cannot directly interact with the DOM. Communication must go through the Web Worker’s postMessage method.
  • WebSocket:
    Creates an open connection between a client and a server, allowing persistent two-way communication over a single connection. Ideal for any situation where you currently use long-polling such as chat apps, online games, or sports tickers. Can directly interact with the DOM. Communication is handled through the WebSocket’s send method.

NTL;WR ;-)

Service Workers

HTML5 Rocks has a nice introduction to Service Workers (aka ServiceWorkers). From that article, the best one-line definition I found was:

Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.

Service Workers are pretty perfect for creating offline-first web apps. They let you interact with the server when you can (to fetch new data from the server, or push updated info back to the server), so your app can work regardless of your user’s connectivity.

For example, an email client could fetch emails when the app loads, then, if the user loses connectivity for a brief period, the app could still continue to register read/unread and deleted states and store new emails to send until connectivity is restored, then send those updates back to the server via a Service Worker. To the user, all the time they were offline, the app continued to work, so they “got stuff done”, and your app just did its job, by collecting changes and updating the server as soon as it could.

While Service Workers cannot directly interact with the DOM, your main JS code can do that based on the messages you receive back from a Service Worker. Service workers also stop when not being used and restart when needed, so there is no persistent “state”; you would need to rely on some form of local storage (localStorage, IndexedDB, etc.) for such persistence. It is important to remember that a Service Worker’s life cycle is completely separate from your webpage.

You can dig a little more deeply into Service Workers, but apparently there is a law that anything published on the web about Service Workers must be created by . :-) That, or he is seriously, madly in love with them. (So much so that, while I would normally use Can I Use to determine the usability of Service Workers, even the Can I Use Service Workers table refers to Jake’s “Is Service Worker Ready?” page to find out the status of Service Workers…)

Service Worker resources:

Web Workers

HTML5 Rocks has a nice introduction to Web Workers (aka Workers). From that article, the best one-line definition I found was:

Workers utilize thread-like message passing to achieve parallelism.

Web Workers are pretty perfect for any web app that has intense functions to perform. They let you push the intense functions into a background thread so your main JS can keep on rocking, like maybe setting up event listeners and other UI interactions. Then, when the intense functions are done, they report back with their results, letting the main JS update the web app.

For example, a site that fetches and displays data in a series of dynamic charts could have each chart fetch its own data via a separate Web Worker. While the Web Workers are fetching, processing, and calculating their data, the main JS could be setting up menus, event listeners, initializing date pickers and custom UI elements, etc. And when each Web Worker is done with its process, it can report back to the main JS with its resulting data to be used to create its respective chart.

While Web Workers cannot directly interact with the DOM, your main JS code can do that based on the messages you receive back from a Web Worker. And as they are completely separate threads, Web Worker code must exist in a separate file and does not have access to your main JS. Workers can also spawn subworkers, to create additional background threads.

Support for Web Workers is quite good, with only IE < 10 and Android < 4.4 deserving any real consideration.

Web Worker resources:

WebSockets

HTML5 Rocks has a nice introduction to WebSockets (aka Sockets). From that article, the best one-line definition I found was:

There is an [sic] persistent connection between the client and the server and both parties can start sending data at any time.

WebSockets are pretty perfect for any web app that needs to communicate frequently with a server, and could benefit from the server being able to communicate directly with the client.

For example, a chat app could create a WebSocket connection so that as each person types, their message is pushed to the server and the server can then send that message directly to the other person(s) in that chat. The previous methods for doing this would be using setTimeout, setInterval and Ajax requests. But these approaches created intensive loops that have to keep asking the server: “Do you have anything yet?” No. “Do you have anything yet?” No. “Do you have anything yet?” No…

So, with WebSockets we finally can directly affect the DOM and, as they are part of the main thread, WebSockets do have access to your main JS.

Support for WebSockets is quite good, with only IE < 10 and Android < 4.4 deserving any real consideration.

WebSockets resources:

Summation

So, while WebSockets and Service Workers kind of overlap, both being used for client-server communications, WebSockets would be used more for continuous communication so both the client and the server can send messages to each other without having to create new connections, and Service Workers would be used more for one-off client-server communications like syncing an app and the database after the app was offline for some time, like a burst that can then be dropped when the sync is completed.

And Web Workers are something completely different, allowing processor-intensive functions to run in a separate, background thread, while allowing the main JS to run and the UI to setup and operate more smoothly while those intensive functions are still running in the background.

Well, I hope this quick look at Service Workers, Web Workers and WebSockets helped clear up the similarities, differences, and purposes of these great new web technologies for you, as much as it did for me! As always, please feel free to drop any questions/thoughts into the comments below; discussion is always fun. :-)

Happy coding,
Atg

15 Responses to The difference between Service Workers, Web Workers and WebSockets

  1. Mark says:

    Great post, but i am still not entirely clear on the difference between Web Workers and Service Workers? they both appear to be the same in terms of functionality? Would someone elaborate further please? thank you.

    • Hey, Mark, thanks for the question.

      Yes, Web Workers and Service Workers do appear to be pretty similar: both work in the background, mimicking multi-threading; both communicate back to your main JS via a postMessage; and neither can directly interact with the DOM. And it is possible that they can both handle some of the same tasks.

      Web Workers are more for heavy JS tasks, the kind of stuff that might greatly slow, or even completely block, your site’s UI. Stuff like compiling or crunching a bunch of data, generating resource-intensive charts or diagrams, etc. This can all be pushed off to a Web Worker, while the main JS goes about some other task(s), and when the Web Worker is done, it will send the completed work back to the main JS to do whatever with.

      Service Workers, once instantiated, monitor any attempts to contact the outside world, so they are more for customizing server communication requests. I have seen people do stuff like pre-download and cache assets, so that when they are needed they can be served them directly from the browser, rather than waiting for the server roundtrip, or storing server communications if a device loses connectivity temporarily, then once the connection is back, pushing and pulling again to get things synced, I have even seen someone used Modernizr to check if a device can handle webp images and then use Service Workers to change the extension for any jpg images to webp images…

      I hope this helps clear things up at least a little. But the best way to get to know them each better, is by digging in and playing with them all to find out what works, what doesn’t, and what makes more sense in various situations.

      Thanks for reading, and for the question!

Leave a Reply

Your email address will not be published. Required fields are marked *