๐ท Web Workers
If you have computation-heavy tasks in your app, you can offload them to a Web Worker (opens in a new tab). Workers are separate threads that runs in the background without blocking the UI, reducing jank in your canvas. You can for instance use Web Workers for pathfinding (opens in a new tab) or physics.
Web Workers rely on the postMessage
and onmessage
API to communicate with the main thread, which means you cannot wait for a particular message to be received and write code in a convenient async
/await
fashion. That's why some libraries have been created to help with the process:
-
Comlink
10k270k/w1y year
-
workerpool
2k5M/w โ Supports pools, Node.js
Supports pools, Node.js -
threads.js
3k92k/w2y years โ Supports pools, observables, Webpack, Node.js
Supports pools, observables, Webpack, Node.js -
troika-worker-utils
120k/w
-
workerize-loader
2k15k/w โ Webpack loader
-
Workerize
4k700/w4y years
-
comlink-loader
6005k/w4y years โ Webpack loader
-
Greenlet
5k600/w4y years
Compare on NPMTrends and Star History (requires a GH token)
About these numbers and colors
import.meta.url
Note that you can use import.meta.url
(opens in a new tab) to reference a Web Worker file from your filesystem:
const worker = new Worker(new URL('./worker.ts', import.meta.url))