๐ท 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:
- Comlink9k196k/w
-
workerpool2k5M/w โ Supports pools, Node.jsSupports pools, Node.js
-
threads.js3k116k/w2y years โ Supports pools, observables, Webpack, Node.jsSupports pools, observables, Webpack, Node.js
- troika-worker-utils106k/w
- workerize-loader2k17k/w โ Webpack loader
- Workerize4k700/w3y years
- comlink-loader6007k/w3y years โ Webpack loader
- Greenlet5k900/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))