Service Worker and Web Workers

Posted on October 2, 2021
Tags: javascript

1 Quick summary

2 Web workers

2.1 self

  • self in the main thread means the window object
  • self for webworker thread means the ServiceWorkerGlobalScope
  • Webworkers have no access to DOM elements
  • The main thread is the only thread that can create web workers with const x = new Worker("henchman.js)

2.2 How to create

  • We need to create separate js file for a webworker
  • We create a henchman.js file for webworker and self.addEventListener(..) allows Webworkers to respond to events

2.3 Compared to multiprocessing

  • Webworkers have no mutex, semaphore or shared memory
  • They listen to events and send messages

3 What are Service Worker?

Browser <—> ServiceWorker/Cache <—>

/* service-worker.js */

// Install 
self.addEventListener('install', function(event) {
    // ...
});

// Activate 
self.addEventListener('activate', function(event) {
    // ...
});

// Listen for network requests from the main document
self.addEventListener('fetch', function(event) {
    // ...
});