Types of Worker
Type | Worker | ||
---|---|---|---|
Web Worker | Service Worker | ||
Dedicated Worker | Shared Worker | ||
Amount | Multiple per tab | One per origin | |
Scope | One tab | One origin | One origin |
Lifetime | Depends on tab | Depends on tabs | Depends on browser |
Usage | Parallelism | Offline experience, Background sync, Push notifications |
They can’t access the DOM.
Example (Dedicated Worker)
<html> <head> <script src="script.js"></script> </head> <body> <img src="https://media.giphy.com/media/lKKXOCVviOAXS/giphy.gif"/> <p>Take a nap: <button onclick="takeNapSync()">Sync</button> <button onclick="takeNapAsync()">Async</button> </p> </body> </html>
const napTimeInMs = 3000; var worker = new Worker('worker.js'); worker.onmessage = function(event) { alert(event.data); } function sleep(timeInMs) { var start = new Date().getTime(); var expire = start + timeInMs; while (new Date().getTime() < expire) {} } function takeNapSync() { // Is blocking the UI-Thread sleep(napTimeInMs); alert("Nap done."); } function takeNapAsync() { // Isn't blocking the UI-Thread worker.postMessage(napTimeInMs); }
function sleep(timeInMs) { var start = new Date().getTime(); var expire = start + timeInMs; while (new Date().getTime() < expire) {} } onmessage = function(event) { sleep(event.data); postMessage("Nap done."); }