Atlaslog
Atlaslog / Field Notes / Build & deployment
Field note · Build & deployment

Moving aggregation into a Worker fails with document is not defined

Quick answer

The Worker entry imports a module chain that touches window or document at module scope, so it dies before any message arrives. Map libraries probe for window or create a canvas merely by being imported.

Last verified 2026-11-03 · Multiple versions · Cite this page
Applies to: Web Worker / Vite
Symptom
Checklist
  1. Read the bottom of the stack trace to find the module touching DOM at import time.
  2. Replace the Worker body with one console.log to confirm the Worker itself starts.
  3. Re-enable imports one at a time to isolate the offending dependency.
  4. Check whether a component file with UI imports was moved into the Worker wholesale.
Fix

Keep only pure computation such as gridAggregate in the Worker module with no map library imports, start it with new Worker(new URL('./workers/aggregate.worker.js', import.meta.url), { type: 'module' }), and use OffscreenCanvas via transferControlToOffscreen if drawing is needed.

Code
Uncaught ReferenceError: document is not defined
    at leaflet-src.esm.js:4210

Uncaught ReferenceError: window is not defined
    at proxied-module.js:1
console.log('worker 启动', typeof self);
// import './geo/aggregate.js';
// import 'leaflet';
Watch out
All 120 field notesChinese originalRunnable examples
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Cite this page

Atlaslog (2026). Moving aggregation into a Worker fails with document is not defined. https://www.jingweizhi.com/en/cookbook/webworker-dom-library.html (accessed 2026-11-03).