web workers – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Thu, 03 Nov 2022 12:57:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 web workers – CSS-Tricks https://css-tricks.com 32 32 45537868 The Difference Between Web Sockets, Web Workers, and Service Workers https://css-tricks.com/the-difference-between-web-sockets-web-workers-and-service-workers/ https://css-tricks.com/the-difference-between-web-sockets-web-workers-and-service-workers/#comments Thu, 03 Nov 2022 12:56:58 +0000 https://css-tricks.com/?p=374731 Web Sockets, Web Workers, Service Workers… these are terms you may have read or overheard. Maybe not all of them, but likely at least one of them. And even if you have a good handle on front-end development, there’s a …


The Difference Between Web Sockets, Web Workers, and Service Workers originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Web Sockets, Web Workers, Service Workers… these are terms you may have read or overheard. Maybe not all of them, but likely at least one of them. And even if you have a good handle on front-end development, there’s a good chance you need to look up what they mean. Or maybe you’re like me and mix them up from time to time. The terms all look and sound awful similar and it’s really easy to get them confused.

So, let’s break them down together and distinguish Web Sockets, Web Workers, and Service Workers. Not in the nitty-gritty sense where we do a deep dive and get hands-on experience with each one — more like a little helper to bookmark the next time I you need a refresher.

Quick reference

We’ll start with a high-level overview for a quick compare and contrast.

FeatureWhat it is
Web SocketEstablishes an open and persistent two-way connection between the browser and server to send and receive messages over a single connection triggered by events.
Web WorkerAllows scripts to run in the background in separate threads to prevent scripts from blocking one another on the main thread.
Service WorkerA type of Web Worker that creates a background service that acts middleware for handling network requests between the browser and server, even in offline situations.

Web Sockets

A Web Socket is a two-way communication protocol. Think of this like an ongoing call between you and your friend that won’t end unless one of you decides to hang up. The only difference is that you are the browser and your friend is the server. The client sends a request to the server and the server responds by processing the client’s request and vice-versa.

Illustration of two women representing the browser and server, respectively. Arrows between them show the flow of communication in an active connection.

The communication is based on events. A WebSocket object is established and connects to a server, and messages between the server trigger events that send and receive them.

This means that when the initial connection is made, we have a client-server communication where a connection is initiated and kept alive until either the client or server chooses to terminate it by sending a CloseEvent. That makes Web Sockets ideal for applications that require continuous and direct communication between a client and a server. Most definitions I’ve seen call out chat apps as a common use case — you type a message, send it to the server, trigger an event, and the server responds with data without having to ping the server over and again.

Consider this scenario: You’re on your way out and you decide to switch on Google Maps. You probably already know how Google Maps works, but if you don’t, it finds your location automatically after you connect to the app and keeps track of it wherever you go. It uses real-time data transmission to keep track of your location as long as this connection is alive. That’s a Web Socket establishing a persistent two-way conversation between the browser and server to keep that data up to date. A sports app with real-time scores might also make use of Web Sockets this way.

The big difference between Web Sockets and Web Workers (and, by extension as we’ll see, Service Workers) is that they have direct access to the DOM. Whereas Web Workers (and Service Workers) run on separate threads, Web Sockets are part of the main thread which gives them the ability to manipulate the DOM.

There are tools and services to help establish and maintain Web Socket connections, including: SocketCluster, AsyncAPI, cowboy, WebSocket King, Channels, and Gorilla WebSocket. MDN has a running list that includes other services.

More Web Sockets information

Web Workers

Consider a scenario where you need to perform a bunch of complex calculations while at the same time making changes to the DOM. JavaScript is a single-threaded application and running more than one script might disrupt the user interface you are trying to make changes to as well as the complex calculation being performed.

This is where the Web Workers come into play.

Web Workers allow scripts to run in the background in separate threads to prevent scripts from blocking one another on the main thread. That makes them great for enhancing the performance of applications that require intensive operations since those operations can be performed in the background on separate threads without affecting the user interface from rendering. But they’re not so great at accessing the DOM because, unlike Web Sockets, a web worker runs outside the main thread in its own thread.

A Web Worker is an object that executes a script file by using a Worker object to carry out the tasks. And when we talk about workers, they tend to fall into one of three types:

  • Dedicated Workers: A dedicated worker is only within reach by the script that calls it. It still executes the tasks of a typical web worker, such as its multi-threading scripts.
  • Shared Workers: A shared worker is the opposite of a dedicated worker. It can be accessed by multiple scripts and can practically perform any task that a web worker executes as long as they exist in the same domain as the worker.
  • Service Workers: A service worker acts as a network proxy between an app, the browser, and the server, allowing scripts to run even in the event when the network goes offline. We’re going to get to this in the next section.

More Web Workers information

Service Workers

There are some things we have no control over as developers, and one of those things is a user’s network connection. Whatever network a user connects to is what it is. We can only do our best to optimize our apps so they perform the best they can on any connection that happens to be used.

Service Workers are one of the things we can do to progressively enhance an app’s performance. A service worker sits between the app, the browser, and the server, providing a secure connection that runs in the background on a separate thread, thanks to — you guessed it — Web Workers. As we learned in the last section, Service Workers are one of three types of Web Workers.

So, why would you ever need a service worker sitting between your app and the user’s browser? Again, we have no control over the user’s network connection. Say the connection gives out for some unknown reason. That would break communication between the browser and the server, preventing data from being passed back and forth. A service worker maintains the connection, acting as an async proxy that is capable of intercepting requests and executing tasks — even after the network connection is lost.

A gear cog icon labeled Service Worker in between a browser icon labeled client and a cloud icon labeled server.

This is the main driver of what’s often referred to as “offline-first” development. We can store assets in the local cache instead of the network, provide critical information if the user goes offline, prefetch things so they’re ready when the user needs them, and provide fallbacks in response to network errors. They’re fully asynchronous but, unlike Web Sockets, they have no access to the DOM since they run on their own threads.

The other big thing to know about Service Workers is that they intercept every single request and response from your app. As such, they have some security implications, most notably that they follow a same-origin policy. So, that means no running a service worker from a CDN or third-party service. They also require a secure HTTPS connection, which means you’ll need a SSL certificate for them to run.

More Service Workers information

Wrapping up

That’s a super high-level explanation of the differences (and similarities) between Web Sockets, Web Workers, and Service Workers. Again, the terminology and concepts are similar enough to mix one up with another, but hopefully, this gives you a better idea of how to distinguish them.

We kicked things off with a quick reference table. Here’s the same thing, but slightly expanded to draw thicker comparisons.

FeatureWhat it isMultithreaded?HTTPS?DOM access?
Web SocketEstablishes an open and persistent two-way connection between the browser and server to send and receive messages over a single connection triggered by events.Runs on the main threadNot requiredYes
Web WorkerAllows scripts to run in the background in separate threads to prevent scripts from blocking one another on the main thread.Runs on a separate threadRequiredNo
Service WorkerA type of Web Worker that creates a background service that acts middleware for handling network requests between the browser and server, even in offline situations.Runs on a separate threadRequiredNo

The Difference Between Web Sockets, Web Workers, and Service Workers originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-difference-between-web-sockets-web-workers-and-service-workers/feed/ 3 374731
The State Of Web Workers In 2021 https://css-tricks.com/the-state-of-web-workers-in-2021/ https://css-tricks.com/the-state-of-web-workers-in-2021/#comments Wed, 04 Aug 2021 23:44:06 +0000 https://css-tricks.com/?p=345866 You gotta appreciate the tenacity of Surma. He’s been advocating for Web Workers as a path forward to better-feeling websites for a lot of years now. He’s at it again making sure we all understand the landscape:

[…] regardless


The State Of Web Workers In 2021 originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
You gotta appreciate the tenacity of Surma. He’s been advocating for Web Workers as a path forward to better-feeling websites for a lot of years now. He’s at it again making sure we all understand the landscape:

[…] regardless of where you look, multithreading is used everywhere. iOS empowers developers to easily parallelize code using Grand Central Dispatch, Android does this via their new, unified task scheduler WorkManager and game engines like Unity have job systems. The reason for any of these platforms to not only support multithreading, but making it as easy as possible is always the same: Ensure your app feels great.

Surma, “The State Of Web Workers In 2021”

So pretty much every platform has its own version of multi-threading, including the web. It’s just that on the web we have to sort of “fight” against the single-threaded nature of JavaScript by using Web Workers (which are “universally supported” if you’re wondering about that). The question is: use them how and for what? For the latter, Surma shows off an example of a game where “the entire app state and game logic is running in a worker.” For the former, the helper library comlink looks like a big reduction in toil.

Personally, I wish popular tooling would just kinda… do it. I don’t know what that really looks like, but it kinda feels like developer outreach isn’t really moving the needle on this. What if popular tooling like Apollo — which is in charge of a lot of “app state” — were to magically handle all of that off the main thread. Does that make sense? Is it possible?

To Shared LinkPermalink on CSS-Tricks


The State Of Web Workers In 2021 originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-state-of-web-workers-in-2021/feed/ 3 345866
“Off The Main Thread” https://css-tricks.com/off-the-main-thread/ Tue, 10 Sep 2019 14:33:41 +0000 https://css-tricks.com/?p=295481 JavaScript is what they call “single-threaded.” As Brian Barbour puts it:

This means it has one call stack and one memory heap.

We all feel a symptom of that regularly in the form of performance jank and non-interactivity on …


“Off The Main Thread” originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
JavaScript is what they call “single-threaded.” As Brian Barbour puts it:

This means it has one call stack and one memory heap.

We all feel a symptom of that regularly in the form of performance jank and non-interactivity on elements or entire sites. If we give JavaScript lots of jobs and it gets really busy doing them, then it’s not doing other things, like, say, handling our event handlers quickly.

There has been an interesting point/counter-point combo recently along these lines.

Das Surma has been advocating for moving as much JavaScript off the main thread as you possibly can. In fact, when it comes to using Web Workers, he suggests:

You should always use Web Workers.

Web Workers being the primary way to run JavaScript off the main thread. Paul Lewis likens the problem to The 9am Rush Hour:

The worst time of day to travel. For many it’s not possible to travel at any other time of day because they need to get to work by 9am.

This is exactly what a lot of web code looks like today: everything runs on a single thread, the main thread, and the traffic is bad. In fact, it’s even more extreme than that: there’s one lane from the city center to the outskirts, and quite literally everyone is on the road, even if they don’t need to be at the office by 9am.

I also like how Surma compares other languages in how they often call “main thread” the “UI thread”. If what you are doing is UI-related, do it on the main thread; if it’s not, do it off the main thread. He gets into this on a good episode of The Web Platform Podcast – 194: Off the Main Thread. I could see that being a positive change in the attitude and thinking of JavaScript developers.

An example of getting something off the UI thread: State management.

David Gilbertson must have read that and wrote:

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread). Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

David’s main point, it seems to me, is that some of the hefty JavaScript things we need to do are in response to user-initiated actions where the user needs to wait for things to finish anyway, so an unresponsive UI during that time is OK. But for anything that isn’t user-initiated — and takes longer than say 100ms — he agrees a Web Worker is helpful.

(Looking at that 100ms thing, it’s worth noting that a major point Surma is making is that the world is full of low-end phones — and who knows what 100ms on a high-end phone is when translated to on a low-end phone.)

The big trick in getting things off the main thread in JavaScript is using Web Workers. It’s not a hack or anything, Web Workers are quite literally the native API for bringing multiple background threads to JavaScript. Similar to a Service Worker, they are usually in another file:

var myWorker = new Worker('worker.js');

But they don’t have to be – you can inline them or use a lib. The API isn’t awful, but it’s not amazing either. Surma has a library for that: Comlink.

Surma’s crusade on this is quite the long term effort. It was a feature at 2018’s Chrome Summit with A Quest to Guarantee Responsiveness: Scheduling On and Off the Main Thread and again in 2019 with The main thread is overworked & underpaid, but this time with nearly six times the views at the time of this update:

And he’s not alone. Here’s Alex MacArthur on adjusting his thinking about event handlers to accommodate doing things off thread.


“Off The Main Thread” originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
295481