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
Feel free to scroll or jump…
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:
- From above, HTML5 Rocks’ introduction to Service Workers.
- Also from above, Is Service Worker Ready?, maintained by Jake Archibald, is the go-to site for checking the implementation and support in browsers.
- The MDN Service Worker API page, provides all the specs and functionality.
- Using ServiceWorker in Chrome today is a nice walk-through on basic usage of Service Worker.
- YouTube video The ServiceWorker: The network layer is yours to own.
- Note that the Service Worker W3 spec is still a Working Draft.
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:
- From above, HTML5 Rocks’ introduction to Web Workers.
- Also from above, Can I Use page for Web Workers, for checking browser support.
- The MDN Web Worker API page, provides all the specs and functionality.
- Note that the Web Worker W3 spec is still a Working Draft.
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. :-)
Thanks for the post and the links. Very useful.
Very useful post. Simple amazing! Thanks!!
Nice article thanks for posting.
Thank so much. Your article was excellent
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
webpimages and then use Service Workers to change the extension for any
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!
Terrific explanation and clarified a few vital points for me.
Thank you. Mark.
Awesome Aaron, pretty neat explanation on workers.
Best explanation to be found anywhere of the differing functionalities! Thanks for clarifying!
Wow, thanks, John! :-)
Thanks for the publication. Kudos!!!
I’m reading this awesome article at 3 pm and for future readers who want night theme.
Kutsan, it only took me 5+ years, but your “night theme” is finally here! :-)
Required a bit more than the `filter` & `background`, though not nearly enough to justify the delay…
Anyhow, hope your night reading is a little more enjoyable now!
localStorage is not available in service workers..
Thanks, alex, duly noted, and removed from the article!
Very helpfull !! Thanks
Great Article! Thanks
Thanks so much.
One suggestion tho, is that Service Workers, are actually a “type” of Web Workers. They’re Web Workers dedicated to syncing, pushing and offline stuff.
Aren’t they ?
It looked like it was the case when I read this article on Services Workers : https://developers.google.com/web/fundamentals/getting-started/primers/service-workers
Hey, Remy, thanks for the note.
Kind of like a Maserati and a Mac truck are both vehicles, and each are powerful in their own way, but both serve their own special purpose…
My $.02, thanks again!
tnx. so clear and simple
A very timely explanation for me. Well done.
Thanks for sharing!
Very nice, thank you for sharing!
One of best articles I have ever come across. You cleared my all doubts in a single blog.
Thanks! Great article!
Thank you so much for pointing out the differences and explaining each of them so clearly.