Service Worker and Web Workers
Posted on October 2, 2021
Tags: javascript
1 Quick summary
- Service Worker = Cache
- Web Workers = memoryless Multithread
2 Web workers
2.1 self
self
in the main thread means thewindow
objectself
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 andself.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?
- it’s just a cache
- it’s only useful on the 2nd visit of a website
Browser <—> ServiceWorker/Cache <—>
/* service-worker.js */
// Install
.addEventListener('install', function(event) {
self// ...
;
})
// Activate
.addEventListener('activate', function(event) {
self// ...
;
})
// Listen for network requests from the main document
.addEventListener('fetch', function(event) {
self// ...
; })