Repository navigation
Web Workers
Olivier Biot edited this page Nov 13, 2026
·
1 revision
A Web Worker runs JavaScript on its own thread, away from the page. melonJS can draw from one, onto a canvas the page hands over as an OffscreenCanvas, so the page's own thread stays free.
This needs melonJS 20.14 or later, and is experimental. See Platforms for the other platforms.
The page gives the worker control of its canvas:
// page
const canvas = document.querySelector("canvas");
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker(new URL("./game-worker.js", import.meta.url), { type: "module" });
worker.postMessage({ canvas: offscreen }, [offscreen]);The worker hands it to the application:
// game-worker.js
import { Application, video } from "melonjs";
self.onmessage = async ({ data }) => {
const app = new Application(data.canvas.width, data.canvas.height, {
canvas: data.canvas,
renderer: video.AUTO,
scale: 1,
});
await app.init();
// load assets and start the game as usual
};A worker has no page, and fewer web APIs than one:
- No input of its own. Pointer and keyboard events happen on the page, so the game in the worker doesn't receive them.
-
No sound. A worker has no
AudioorAudioContext: play sound from the page. -
No
Image. melonJS loads PNG and JPEG images withfetchandcreateImageBitmap, which a worker has, so those work. SVG images go throughImage, so they don't: use PNG. -
Size: there is no page to fit, so set the size yourself, as above, with
scale: 1. -
Tiled maps must be JSON (
.tmjand.tsj): XML needsDOMParser, which workers don't have. Thevideoandscriptasset types fail.
So a worker suits drawing that runs on its own: an animated scene, a preview, a background. A game the player plays still needs its input and sound on the page.
- Nintendo Switch (nx.js): the other place melonJS runs without a page
- MDN: OffscreenCanvas and Using Web Workers