🟑 MediumBrowser APIsπŸ“– Theory Question

What are Service Workers and what problems do they solve?

πŸ’‘

Hint

Background JS proxy between app and network β€” enables offline support, push notifications, caching

Full Answer

A Service Worker is a script that runs in the background, separate from the page β€” acting as a network proxy. Enables progressive web app features.

// Registration (main thread)
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(reg => console.log('SW registered:', reg.scope))
    .catch(err => console.error('SW failed:', err));
}

// sw.js β€” the service worker itself
const CACHE = 'v1';
const ASSETS = ['/index.html', '/styles.css', '/app.js'];

// Install β€” pre-cache core assets
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE).then(cache => cache.addAll(ASSETS))
  );
});

// Activate β€” clean old caches
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
    )
  );
});

// Fetch β€” intercept ALL network requests
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(cached => {
      return cached || fetch(event.request); // cache-first strategy
    })
  );
});

Capabilities: Offline caching, background sync, push notifications, intercepting requests, URL routing.

πŸ’‘ Service Workers only run on HTTPS (or localhost). They have no DOM access. They're the foundation of Progressive Web Apps (PWAs). Use Workbox library to simplify service worker code.

More Browser APIs Questions

🟒 EasyWhat is the Fetch API and how do you handle errors correctly?β†’πŸŸ’ EasyWhat is the difference between localStorage, sessionStorage, and cookies?β†’πŸŸ‘ MediumWhat are Web Workers and when should you use them?β†’πŸŸ‘ MediumWhat is the Same-Origin Policy and how does CORS work?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint