MENU
Task
A Web Worker is a JavaScript file running across processor cores(dedicated), browser tabs(shared), sessions(service), and iframes.
A worker script cannot access the DOM objects. Its global members are defined on the 'self' object instead of the 'window' object.
(Launch the FULL-screen mode and press F12 to open the console.)
RESETRUNFULL
RESETRUNFULL
// /shared/worker.js (fixed)
console.log(globalThis.name, globalThis==self); // myWorker true
// console.log(window); // error: undefined
console.log(self); /* DedicatedWorkerGlobalScope {name: 'myWorker',
onmessage: null,
onmessageerror: null,
cancelAnimationFrame: ƒ,
close: ƒ, …} */
<!DOCTYPE><html><body style="height:0">
<p></p>
<script>
document.querySelector("p").innerHTML = (globalThis==self)+" : "+(globalThis==window);
var myWorker = new Worker("/shared/worker.js", { name : "myWorker" });
</script></body></html>
Note that window.postMessage() and the onmessage event work across parent-child windows and iframes too.
A ServiceWorker continues to run in the background even after the user has navigated away from the site. It requires a secure context, ie. HTTPS.
Worker Type | Lifespan |
Dedicated Web Worker | Until closing of tab or navigation to another page. |
Shared Worker | Until closing of all tabs of the site on a browser. |
Service Worker | About one minute after the closing of all tabs of the site on a browser, on a desktop PC. |
(as of 3 Oct, 2020) |