JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
What are the restrictions of web workers on DOM
WebWorkers don't have access to below javascript objects since they are defined in an external files
- Window object
- Document object
- Parent object
Practical Code Example
javascript
// Inside worker.js:
// document.getElementById('heading').textContent = 'Hi'; // ReferenceError: document is not defined!
// window.alert('Notice'); // ReferenceError: window is not defined!
// Workers can only process data and send results back via postMessage:
self.onmessage = (event) => {
const result = event.data * 2; // CPU computation
self.postMessage(result); // send back to main UI thread
};