Making Web Workers enjoyable

By Ravindre Ramjiawan

5 min read

In a single threaded environment Web Workers allow for offloading intensive tasks to keep the main thread free and responsive.

Making Web Workers enjoyable
Authors

Table of Contents

Background

In the dynamic and ever-evolving landscape of web development, developers universally strive to create responsive applications. The goal is to deliver a seamless user experience, maintaining a minimum of 60 frames per second, a benchmark set by the highly responsive1 mobile apps that users have become accustomed to. Furthermore, unhandled user input can lead to a subpar user experience, underscoring the importance of comprehensive input handling in the quest for optimal responsiveness. However, this can often present a significant challenge due to the single-threaded2 nature of JavaScript.

In the current era, with an abundance of frontend libraries at our disposal, it’s increasingly easy to compromise on performance and responsiveness as these libraries consume substantial resources. This implies that when JavaScript is tasked with heavy computations or data processing, it can result in an unresponsive or janky user interface (UI), leading to user dissatisfaction. Therefore, it is crucial to manage resources effectively to ensure a smooth and responsive UI.

Web Workers

Web Workers3 were first published by the World Wide Web Consortium (W3C)4 and the Web Hypertext Application Technology Working Group (WHATWG)5 on April 3, 2009. The W3C and the WHATWG conceptualize web workers as scripts that operate continuously. These scripts are designed to run without being disrupted by other scripts that react to user interactions such as clicks. By ensuring these workers are not interrupted by user activities, web pages can maintain their responsiveness while concurrently executing extensive tasks in the background. This approach allows for a smoother and more efficient user experience.

Web Workers are not to be confused with Service Workers6. Service Workers serve a different purpose and act as proxy server to enable offline experiences by intercepting network requests. Service Workers also run in a worker context meaning that they run in a separate thread.

How to create a Web Worker

To make use of a Web Worker you have to create a new Worker by calling the Worker() constructor and passing the URL of a script file that will be executed in the Worker thread.

// Vanilla
const worker = new Worker('heavy-calculation-script.js')

Nowadays with the usage of web bundlers such as Webpack7 or Vite8 Web Workers require a relative module url.

// Bundlers
const worker = new Worker(new URL('./heavy-calcluation-script.js', import.meta.url))

How to communicate with a Web Worker

Once you have created your Web Worker you are now able to send and receive messages from it. To send messages you make use of the postMessage() method and to listen for messages you can use addEventListener() or set a callback directly on the onmessage property.

const worker = new Worker('heavy-calculation-script.js')

// Sending a message to the Web Worker
worker.postMessage('Hello from main thread!')

// Listening for messages from the Web Worker
worker.onmessage = ({ data }: MessageEvent) => {
  console.log(data) // Logs: Hello from worker!
}

// Using event listeners
worker.addEventListener('message', ({ data }: MessageEvent) => {
  console.log(data) // Logs: Hello from worker!
})

You can send anything that is serializable9 when using postMessage(). JavaScript uses the structured clone algorithm10 to perform copying complex objects.

// heavy-calculation-script.js Web Worker

// Sending a message to the Main Thread
self.postMessage('Hello from worker!')

self.addEventListener('message', ({ data }: MessageEvent) => {
  console.log(data) // Logs: Hello from main thread!
})

In the context of a web worker self11 refers to an object that points to current Web Worker context. It is a reliable way to reference the worker context, unlike the this keyword, which can behave unpredictably in various situations. Normally when using this in the global execution context12 will refer to the Window13 object.

Drawbacks of Web Worker communication

Whilst the Web Worker API to send and receive messages gets the job done it is not very developer friendly because of its low-level API. It requires a lot of manual management of message routing and payload marshalling14. There are certain patterns that seem to work nicely with postMessage() such as the Flux15 pattern but there are better libraries out there that can make the use Web Workers a lot more enjoyable and intuitive.

Comlink16 is a tiny library developed by Google. Its primary function is to simplify the process of working with Web Workers by eliminating the complexities associated with using postMessage(). It achieves this by adopting an RPC (Remote Procedure Call)17 style for message transmission and leveraging JavaScript Proxies18 that maintain a reference to the original target. In essence, Comlink enables seamless access to any element from the Main Thread within a Web Worker and vice versa. This bidirectional accessibility significantly enhances the developer experience. Furthermore, when used together with TypeScript19 it supports autocomplete features, making coding even more efficient and enjoyable.

Comlink provides a set of functions that help connect the main thread to the Web Worker and vice versa is fairly straight forward as shown below. The wrap() function wraps the Worker and takes the other end of a Message Channel20 as an argument and returns a proxy. This proxy will have all properties and functions of the exposed value from the other thread. However, access to these properties and function invocations are inherently asynchronous. This means that a function that would normally return a number will now return a Promise()21 for a number.

import { wrap } from 'comlink'

// Create Web Worker
const worker = new Worker('heavy-calculation-script.js')

// Wrap the Web Worker using the wrap method from Comlink
const wrappedWorker = wrap(worker)

// Call any exposed methods from your Web Worker
// Since its a Promise you can use either await or then
wrappedWorker.exposedMethod().then(console.log) // Logs: 5

The expose() method from Comlink is used to make a local object available to the other end of the Message Channel. It can be viewed as the Comlink equivalent of export. This method takes an object and exposes it to the other thread, allowing the other thread to access its properties and methods.

// heavy-calculation-script.js Web Worker
import { expose } from 'comlink'

const api = {
  exposedMethod() {
    return 5
  },
}

// Call expose from Comlink to expose anything you like for the Main Thread to have access to
expose(api)

Conclusion

I hope this gives a better understanding on how Web Workers can help with offloading heavy computations, intensive tasks or long-running pieces of code. This allows for the Main Thread to run as efficient and responsive as possible for not only a better user experience but also a great developer experience when using libraries such as Comlink.

Footnotes

  1. https://en.wikipedia.org/wiki/Responsiveness

  2. https://en.wikipedia.org/wiki/Thread_(computing)

  3. https://en.wikipedia.org/wiki/Web_worker

  4. https://www.w3.org/

  5. https://whatwg.org/

  6. https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

  7. https://webpack.js.org/guides/web-workers/

  8. https://v3.vitejs.dev/guide/features.html#web-workers

  9. https://en.wikipedia.org/wiki/Serialization

  10. https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm

  11. https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self

  12. https://en.wikipedia.org/wiki/Scope_(computer_science)

  13. https://developer.mozilla.org/en-US/docs/Web/API/Window

  14. https://en.wikipedia.org/wiki/Marshalling_(computer_science)

  15. https://facebookarchive.github.io/flux/

  16. https://github.com/GoogleChromeLabs/comlink

  17. https://en.wikipedia.org/wiki/Remote_procedure_call

  18. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

  19. https://en.wikipedia.org/wiki/TypeScript

  20. https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel

  21. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


Upcoming events

  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋‍♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design

Share