How to Use Web Workers (Step-by-Step Guide)

An introduction to using Web Workers, including benefits, implementation details, and references to help you use Web Workers more efficiently.

Jan 31, 2022 · 1 min read · 191 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

JavaScript runs in a single thread. If the frontend has blocking computations, the UI can feel sluggish. To improve the experience, you can offload that work to a Web Worker. You could also move the work to the backend; which to choose depends on the scenario and scalability. I recently hit this in a web project and decided to solve it on the frontend—here are my notes on using Web Workers.

Setup

tsconfig.json

Add Web Worker type declarations.

tsconfig.json

"lib": [
      "webworker",
      "dom",
      "dom.iterable",
      "esnext"
    ],

worker-plugin configuration

To bundle/load worker modules, configure the plugin.

const WorkerPlugin = require('worker-plugin');

plugins:[
			...
      new WorkerPlugin()
      ...
]

Import the worker in app code

export const myWorker = new Worker('./worker', { type: 'module' });

 myWorker.postMessage(JSON.stringify({
        data: detail,
      }));
      myWorker.onmessage = ({ data }: { data: WebWorkerResponse }) => {
      
      };

Worker implementation

(self as DedicatedWorkerGlobalScope).onmessage = function ({ data }) {
  const req = JSON.parse(data) as WebWorkerRequest;
  const res = {
    type: req.type,
    data: {},
  };
  postMessage(res);
};

Current Issues

Debugging isn’t set up yet; for now, console logging is the fallback.

Final Thoughts

That’s the basic usage of Web Workers.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover