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…
- Getting Things Done with WebSockets and Web Workers is an online chapter from Learning HTML5 Game Programming.
- 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…).
- 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
- 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
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
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 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 Jake Archibald. 🙂 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:
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:
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
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.
- From above, HTML5 Rocks’ introduction to WebSockets.
- Also from above, Can I Use page for WebSockets, for checking browser support.
- The MDN WebSockets API page, provides all the specs and functionality.
- WebSockets.org is probably all you would ever need to know about WebSockets…
- Socket.io is a pre-built, open-source, downloadable, “real-time bidirectional event-based communication” that “works on every platform, browser or device, focusing equally on reliability and speed”…
- Note that the WebSockets W3 spec is still a Working Draft.
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. 🙂