Introduction to Service Workers

Kevin Kurniawan
Blibli.com Tech Blog
2 min readJun 26, 2022

A service worker is a JavaScript that gets registered with the browser. It stays registered with the browser even when offline. Service worker can load content event with no connection.

About Service Worker

These are some points of how the service worker works:

  • The service worker can’t directly access the DOM. To communicate with the page, we can use postMessage method and add message listener on the page.
  • Service worker is programmable network proxy. It can control network request from and/or response to our page.
Normal Request/Response
Request/Response with Service Worker
  • The service worker will be terminated when not in use, but it will be restarted when next needed.
  • Service workers make use of JavaScript Promises. If you are new to Promises, please check this out.
  • Our site needs to be served over HTTPS to use service worker. The concern is because service workers can intercept network requests and modify responses and the HTTPS will avoid “man-in-the-middle” attacks.

Service Worker Usage

These are some examples of the usage of Service Worker:

  • Caching assets
    We can caching assets that we retrieved from network response before.
  • Caching API calls
    We can caching API response that we retrieved from previous API calls.
  • Push Notifications
    We can send push notifications to our PWA application using service worker.
  • Background data sync & preload
  • Etc

Browser Supports

Reference: https://caniuse.com/serviceworkers (June 26th, 2022)

Service Worker Lifecycle

Service Worker Lifecycle
  • Installing: The first event that will be triggered, only happens once to install the service worker in current browser.
  • Activated: This fires once the old service worker is gone, and your new service worker is able to control clients. A service worker won’t receive fetch or message events until the service worker becomes active.
  • Error: If the service worker is failed to install, it won’t be activated.
  • Idle: This is the idle cycle when there is no events (fetch/message).
  • Fetch/Message: Will be triggered when the is a fetch/message event.
  • Terminated: If there is no events for a while, the service worker will be terminated and restarted when next needed.

References

--

--