Browser Web Workers
3 min read
Following on from my post last week on the fundamentals of JavaScript, I thought I’d delve into Web Workers as a way of running parallel threads. If you haven’t read my previous post, a fundamental takeaway is that JavaScript is single threaded by default (the main thread). The main thread executes functions line by line. This means that if it comes across a task that takes a long time to complete, this will block anything else from being executed.
What is a Web Worker?
- A Web Worker is a JavaScript process that runs in the background of a webpage.
- It is a separate JavaScript thread, with an isolated JavaScript scope, that allows us to run work in parallel (not to be confused with parallel processing though).
- It can therefore be used to offload computationally expensive work that may block the main thread.
- As a Web Worker has an isolated scope, they cannot make DOM manipulations or access variables and functions in the main script.
How does a Web Worker work?
- To create a Web Worker, we instantiate a new
Worker
, passing in a path to a JavaScript script. - Passing data between the worker and the main thread is done via the
postMessage
API that effectively sends an event. - The corresponding event listener is
onmessage
. - Remember that the worker has its own scope, so the global object within a worker script is the worker. Any references to
self
refers to the worker.
// mainScript.js
const worker = new Worker('./worker.js')
const someInfo = {
// some data
}
// pass data via postMessage
worker.postMessage(someInfo)
// set up an event listener which executes when postMessage is sent from the worker.js
worker.onmessage = function (result) {
// access any data from the worker via result.data
}
// worker.js
// This will run when mainScript.js calls postMessage
onmessage = function (someInfo) {
// run some computationally expensive function
// once completed..send result
const result = 'Computation done'
postMessage(result)
}
Other Workers
- Service Worker - this is similar to a Web Worker but used as a proxy server between web applications, the browser, and the network. A great use for them are for intercepting network requests, creating complex caching behaviour, thus enabling efficient offline experiences.
- Worklet - lightweight version of a Web Worker that provide access to low level parts of the rendering pipeline e.g. audio and graphics.