InterviewHubPRO
Section Overview
Q35

Question 35 of 521

Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

7%
JavaScript Internals (521 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

What is a service worker

A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.

Practical Code Example

javascript
// Registering a Service Worker in main browser thread:
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/service-worker.js')
      .then((reg) => console.log('ServiceWorker registered with scope:', reg.scope))
      .catch((err) => console.error('ServiceWorker registration failed:', err));
  });
}