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.
Symptom
- Uncaught ReferenceError: document is not defined at leaflet-src.esm.js:4210 in the Worker context.
- Uncaught ReferenceError: window is not defined at proxied-module.js:1.
- The main thread never receives a message and onmessage is never called.
Checklist
- Read the bottom of the stack trace to find the module touching DOM at import time.
- Replace the Worker body with one console.log to confirm the Worker itself starts.
- Re-enable imports one at a time to isolate the offending dependency.
- 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:1console.log('worker 启动', typeof self);
// import './geo/aggregate.js';
// import 'leaflet';
Watch out
- Importing Leaflet in the Worker just to reuse a helper type still executes the module and throws at load.
- Trying to create a DOM canvas in the Worker instead of using transferControlToOffscreen fails with document is not defined.
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
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).