Understanding Web Workers, SharedWorker, and ServiceWorker in Frontend Development
This article explains the concepts, creation methods, communication APIs, debugging techniques, and typical use cases of ordinary Web Workers, SharedWorkers, and ServiceWorkers, illustrating how they enable multithreaded computation, cross‑tab data sharing, and offline caching to improve web performance and user experience.
Introduction
JavaScript runs on a single thread, which can cause UI blocking during heavy computations such as video decoding. HTML5 introduces Web Workers to run scripts in separate threads, allowing intensive tasks without affecting the main UI thread. Workers include ordinary Worker, SharedWorker, and ServiceWorker, each suited to different scenarios.
Ordinary Worker
Created with new Worker('./worker.js') , the worker runs in its own thread. Key methods are:
onmessage : listen for messages from the worker.
onmessageerror : handle errors.
postMessage() : send data to the worker.
terminate() : stop the worker.
const worker = new Worker('./worker.js'); // URL must be same‑origin worker.onmessage = function (messageEvent) {
console.log(messageEvent);
}; worker.onmessageerror = function (messageEvent) {
console.log(messageEvent);
}; worker.postMessage({ type: 'start', payload: { count: 666 } }); // send data worker.terminate();Communication uses self inside the worker and postMessage / onmessage on the main thread.
// Worker side
self.onmessage = (messageEvent) => {
const { type, payload } = messageEvent.data;
// process based on type
const result = 0;
this.postMessage(result);
};Additional scripts can be imported with importScripts('constant.js') :
// Worker.js
importScripts('constant.js');
// constant.js
const a = 111;
const b = function () { console.log('test'); };
function c() { console.log('test'); }Debugging is available in the browser’s DevTools under the “Workers” section.
SharedWorker
SharedWorker allows multiple browsing contexts (windows, iframes, other workers) to share a single worker instance. Communication occurs via a port object.
const worker = new SharedWorker("./shareWorker.js"); // same‑origin URLport.onmessage : receive messages.
port.postMessage : send messages.
port.start() : start the port.
port.close() : close the connection.
sharedWorker.port.onmessage = function (messageEvent) {
console.log(messageEvent);
}; sharedWorker.port.postMessage({ type: 'increase', payload: { count: 666 } }); sharedWorker.port.start(); sharedWorker.port.close();SharedWorker also uses importScripts for additional scripts and can be debugged via chrome://inspect/ .
ServiceWorker
ServiceWorker acts as a proxy between the web app, the browser, and the network, enabling offline capabilities, request interception, and resource caching.
// index.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('./serviceWorker.js', { scope: '/page/' })
.then(function (registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
console.log('ServiceWorker registration failed: ', err);
});
});
} // serviceWorker.js
const CACHE_NAME = 'cache-v1';
const urlsToCache = [
'/style/main.css',
'/constant.js',
'/serviceWorker.html',
'/page/index.html',
'/serviceWorker.js',
'/image/131.png',
];
self.oninstall = (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll(urlsToCache);
})
);
};
self.onfetch = (event) => {
event.respondWith(
caches.match(event.request).then(function (response) {
if (response) { return response; }
return fetch(event.request);
})
);
};ServiceWorker can only run on HTTPS or localhost. Debugging is done via chrome://inspect/#service-workers .
Summary Table
Type
Worker
SharedWorker
ServiceWorker
Communication
postMessage
port.postMessage
One‑way via addEventListener on serviceWorker state
Use Cases
Heavy computation
Cross‑tab/iframe data sharing
Resource caching, network optimization
Compatibility
>= IE10, >= Chrome 4
Not IE, Safari, Android, iOS; >= Chrome 4
Not IE; >= Chrome 40
Conclusion
The three worker types serve distinct purposes: ordinary Workers offload intensive calculations to keep the UI responsive, SharedWorkers enable shared state across multiple browsing contexts, and ServiceWorkers provide offline caching and network performance improvements. Selecting the appropriate worker based on the scenario leads to better user experience and more efficient web applications.
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.