Service Worker
ELI5 — The Vibe Check
A Service Worker is a JavaScript script that runs in the background, separate from your web page. It intercepts network requests and can serve cached responses, making your app work offline. Think of it as a personal assistant that intercepts your mail and can deliver old copies when the post office is closed.
Real Talk
A Service Worker is a JavaScript Worker that runs in a separate thread from the main browser thread, acting as a programmable network proxy. It can intercept and handle fetch requests, manage caches via the Cache API, and enable offline functionality, background sync, and push notifications. It requires HTTPS.
Show Me The Code
// service-worker.js
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request)
})
)
})
When You'll Hear This
The Service Worker caches assets so the app works offline.,Service Workers only run on HTTPS (or localhost).,Workbox is a library that simplifies Service Worker caching strategies.
Related Terms
Fetch
Fetch is the modern, built-in JavaScript way to make HTTP requests to APIs. You tell it a URL, it goes and gets the data, and you handle the response.
PWA (PWA)
A PWA is a website that pretends to be an app.
Web Worker
JavaScript normally runs on one thread, which means heavy computation freezes your UI.