This repository contains bindings for the Web Workers API.
Read more about these here, but keep in mind these bindings have been improved since this article was written.
The main script creates a new Web Worker from the worker.re
script and posts a message to it. The Web Worker replies back to that message. The main thread listens to that and prints out the message it received from the Web Worker.
main.re
let worker = WebWorkers.create_webworker("worker.bs.js");
let msg = {"text": "Hello world"};
WebWorkers.postMessage(worker, msg);
let msgBackHandler = (e: WebWorkers.MessageEvent.t) => {
Js.log("I am the main thread and I have received a message back from the worker:");
Js.log(WebWorkers.MessageEvent.data(e))
};
WebWorkers.onMessage(worker, msgBackHandler);
worker.re
WebWorkers.setWorkerOnMessage(
WebWorkers.self,
(e: WebWorkers.MessageEvent.t) => {
Js.log("I am the Web Worker and I have received a message:");
Js.log(WebWorkers.MessageEvent.data(e));
WebWorkers.postMessageFromWorker("my result")
}
);
- Install the bindings using
npm install --save bs-webworkers
- Add the bindings to
bsconfig.json
:
{
"bs-dependencies": [
"bs-webworkers"
]
}
Look in the example/
directory for an example of how to use the bindings.
npm install
npm run build
npm install
npm run test
npm install
npm run example
The full Web Workers API is still not yet implemented (e.g. Shared Workers, Service Worker, WorkerNavigator, WorkerLocation, etc.). PRs are welcome!