Web Workers
Web Workers allows you to run JavaScript code in a separate thread, which is useful for offloading heavy tasks from the main thread. This can be useful for tasks like physics calculations, AI, or other heavy computations.
If you want to learn more about Web Workers, you can read the MDN Web Docs.
Implementation status
Web Workers are supported in JSAR but not completely, the following are the implemented Worker types:
Getting started
To create a new Worker, you first need an entry point file for the worker:
js
console.info('worker.js loaded');
onmessage = function(e) {
if (e.data.text === 'foo') {
postMessage('bar');
}
};
Then, you can create a new Worker
instance in your main script:
html
<html>
<head>
<meta charset="utf-8" />
<title>Web Workers</title>
<script>
const worker = new Worker('worker.js');
worker.onmessage = (event) => {
console.log('Received message from worker:', event.data);
};
worker.postMessage({ text: 'foo' });
</script>
</head>
<body>
</body>
</html>
After opening the index.html
file in JSAR, you should see the message Received message from worker: bar
in the console.
Supported Web APIs
The following Web APIs are supported in Web Workers:
- Objects
- Classes
- Global functions