This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Web Workers Cheatsheet

A quick reference guide for HTML5 Web Workers: worker instantiation, postMessage communication, message events, and structured clone algorithm.

· Published

Web Workers provide a simple means for web content to run scripts in background threads without interfering with the user interface.

Background Threading

Client Thread

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

worker.onmessage = function (event) {
  console.log('Received from worker:', event.data);
};

worker.postMessage('hello from main thread!');

Messages can be any data type supported by the Structured Clone Algorithm (objects, arrays, strings, numbers, blobs, typed arrays).

Worker Thread

// Inside worker.js
self.onmessage = function (event) {
  console.log('Received in worker:', event.data);
  self.postMessage({ msg: 'response from worker' });
};

MessageEvent Structure

bubbles: false
cancelBubble: false
cancelable: false
clipboardData: undefined
currentTarget: Worker
data: "Hello"             // Transferred payload
defaultPrevented: false
eventPhase: 0
lastEventId: ""
origin: ""
ports: []
returnValue: true
source: null
srcElement: Worker
target: Worker
timeStamp: 1344821022383
type: "message"

These fields describe the properties available on the MessageEvent object in onmessage.

Related topics