Posted on

Web Workers and the DOM

Web workers do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object

main.js runs in the main UI thread

var worker = new Worker("worker.js")
woker.onmessage = function(event) {
    document.getElementById("result").innerHTML = event.data
}
// Post message to the worker
worker.postMessage({"cmd": "start", "msg": "Hello"}) 

worker.js runs in a separate thread

self.onmessage = function(event) {
    var data = event.data
    self.postMessage(data.cmd + " " + data.msg)
}

Note: There are two ways to stop a worker: by calling worker.terminate() from the main UI thread or by calling self.close() inside of the worker thread.

Use Transferable objects to efficiently pass binary data between main and worker thread without copying the data. The usual FileBlobArrayBuffer, and JSON objects will be copied between main thread and worker thread, making them more resource expensive.