What is a service worker?

Technology CommunityCategory: PWAWhat is a service worker?
VietMX Staff asked 5 months ago

service worker is a specific type of JS Script, which runs in the background of the user’s browser. It acts like a proxy server exists between your app, the browser and the network. Among other things, service workers allow apps to continue functioning offline in case the user loses internet connection.

Service Workers are a virtual proxy between the browser and the network. They finally fix issues that front-end developers have struggled with for years — most notably how to properly cache the assets of a website and make them available when the user’s device is offline.

They run on a separate thread from the main JavaScript code of our page, and don’t have any access to the DOM structure. This introduces a different approach from traditional web programming — the API is non-blocking, and can send and receive communication between different contexts. You are able to give a Service Worker something to work on, and receive the result whenever it is ready using a Promise-based approach.

They can do a lot more than “just” offering offline capabilities, including handling notifications, performing heavy calculations on a separate thread, etc. Service workers are quite powerful as they can take control over network requests, modify them, serve custom responses retrieved from the cache, or synthesize responses completely.