Creating a worker

Introduction

Web workers run JavaScript on a background thread. This reference covers creating workers, two-way messaging, transferable objects, and shutdown.

Classic and module workers

// Classic script: the default
const worker = new Worker('worker.js')

// Module worker: supports import statements
const moduleWorker = new Worker('worker.js', {
  type: 'module'
})

Classic workers load dependencies with importScripts; module workers use import, are fetched with CORS, and run in strict mode. The script URL must be same-origin, or a blob: or data: URL.

See: Worker()

Constructor options

OptionDefaultEffect
type'classic'Classic script or 'module'
name''Debugger name for the worker scope
credentials'same-origin'Module imports: 'omit', 'include'

credentials only applies to module workers; it controls whether imports send cookies.

See: Worker() options

Inline worker

const source = 'onmessage = (e) => postMessage(e.data * 2)'
const url = URL.createObjectURL(
  new Blob([source], { type: 'text/javascript' })
)
const worker = new Worker(url)

A blob: URL inherits the page's origin, so the worker stays same-origin. Useful for demos and code built at runtime.

See: Blob

Worker kinds

KindConstructorReached from
Dedicatednew Worker(url)The creating script only
Sharednew SharedWorker(url)Many contexts, via .port
Servicenavigator.serviceWorker.register(url)Pages it controls

This sheet covers dedicated workers. A shared worker talks through a MessagePort; a service worker intercepts network requests.

See: Web Workers API

Messaging

Send from the page

const worker = new Worker('worker.js')

worker.onmessage = ({ data }) => console.log(data)
worker.postMessage({ task: 'parse', text: 'a,b,c' })

postMessage() takes one value, so send an object for several fields. Payloads are copied with structured clone, which supports cyclic references but not functions or DOM nodes.

See: Worker.postMessage()

Send from the worker

worker.js

self.onmessage = ({ data }) => {
  self.postMessage(data.text.split(','))
}

self is the worker's global scope, so postMessage and onmessage work without the prefix.

See: DedicatedWorkerGlobalScope.postMessage()

Message event fields

FieldValue
dataThe cloned payload
origin'' for dedicated workers
sourcenull for dedicated workers
portsMessagePorts transferred with the message
lastEventId'' for worker messages

Destructure data for the payload. origin and source are empty for dedicated workers; use a MessageChannel when you need to identify senders.

See: MessageEvent

Direct channels

const worker = new Worker('worker.js')
const { port1, port2 } = new MessageChannel()

worker.postMessage({ port: port2 }, [port2])
port1.onmessage = ({ data }) => console.log(data)

Transferring a port into the worker gives you a private pipe, alongside the shared onmessage handler. Each side posts on its own port.

See: MessageChannel

Transferables

Move a buffer

Main thread

const worker = new Worker('worker.js')
const buffer = new ArrayBuffer(1024 * 1024)

worker.postMessage(buffer, [buffer])
console.log(buffer.byteLength) // 0, detached

In the worker

self.onmessage = ({ data }) => {
  self.postMessage(data, [data]) // move it back
}

The second argument lists resources to move rather than copy. Ownership passes to the receiver, and the sender's copy is detached. Typed arrays are cloned, so transfer their buffer instead.

See: Transferable objects

What can be transferred

ObjectUse
ArrayBufferRaw memory; moves without copying
MessagePortEither end of a MessageChannel
ImageBitmapDecoded image for canvas work
OffscreenCanvasCanvas rendered off the DOM thread
ReadableStreamStreams, with their locks
MediaStreamTrackOne track from a media stream
RTCDataChannelA WebRTC data connection

Plain objects, arrays, and typed arrays are cloned; only these handles move.

See: Transferable objects

Loading code

importScripts

// worker.js (classic only)
importScripts('utils.js', 'parsers.js')

self.onmessage = ({ data }) => self.postMessage(parse(data))

importScripts() loads and runs scripts synchronously, in order, before the next statement. It throws a TypeError in module workers.

See: importScripts()

Module imports

// worker.js (type: 'module')
import { parse } from './parse.js'

self.onmessage = ({ data }) => self.postMessage(parse(data))

Module workers use import statements, resolved before any code runs. Dependencies are fetched with CORS, so cross-origin files need Access-Control-Allow-Origin.

See: JavaScript modules

Lifecycle

Catch errors

const worker = new Worker('worker.js')

worker.addEventListener('error', (event) => {
  console.error(event.message, event.filename, event.lineno)
})

The error event fires for uncaught exceptions in the worker. It carries message, filename, lineno, and colno.

See: error event

Message errors

worker.addEventListener('messageerror', () => {
  console.error('could not deserialize a message')
})

messageerror fires when a received message cannot be deserialized. It is not cancellable.

See: messageerror event

Terminate

const worker = new Worker('worker.js')

worker.terminate()

terminate() stops the worker at once; queued work is dropped and no cleanup hook runs.

See: terminate()

Close from inside

self.onmessage = ({ data }) => {
  if (data === 'stop') return self.close()
  self.postMessage(handle(data))
}

self.close() ends the worker from its own thread and discards queued tasks. close() and self.close() are equivalent here.

See: close()

0 Comments for this cheatsheet. Write yours!