4.3 Web Workers
To run your app in multiple threads
Dedicated Web Workers
dedicated to just one single page/tab
Shared Web Workers
Same-origin policy, but can be shared between different pages or tabs
Workflow
var worker = new Worker("worker0.js");
Communicate using messages
Post messsage to the worker:
worker.postMessage(\\text or object)
Receive message from the worker:
worker.onmessage = event => alert(event.data.firstName)
Post message from the worker
postMessage("Message from a worker")
Worker listening to messages
onmessage = event => //do something with event.data
Errors:
worker.onerror = event => console.log(event.message, event)
Terminate a worker:
worker.terminate();
Include script in the worker file
importScripts('script1.js')
Limitations imposed on Web Workers
Objects available in Web Workers
- The navigator object
- The location object (read-only)
- XMLHttpRequest
- setTimeout()/clearTimeout() and setInterval()/clearInterval()
- The Application Cache
- Importing external scripts using the importScripts() method
- Spawning other Web Workers
Workers do NOT have access to
- The DOM (it's not thread-safe)
- The window object
- The document object
- The parent object