Using Web Workers

· 1 min read · 191 Words · -Views -Comments

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