What is a service worker / Source
A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.
- The install event is the first event a service worker gets, and it only happens once.
- A promise passed to installEvent.waitUntil() signals the duration and success or failure of your install.
- A service worker won't receive events like fetch and push until it successfully finishes installing and becomes "active".
- By default, a page's fetches won't go through a service worker unless the page request itself went through a service worker. So you'll need to refresh the page to see the effects of the service worker.
- clients.claim() can override this default, and take control of non-controlled pages.
- you need HTTPS
navigator.serviceWorker.register('/sw.js')
.then((registration) => {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}
});