Service Worker
Service worker is a worker that run separately in a different thread that's not related to our web app. However it can communicate with our webapp — intercepting events and so on.
Use case:
- Push notification (not real-time)
- Offline caching web app
Setup
In order to use service worker, we need to create a file, let's say sw.js
And then we can register it in our app.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js', {
scope: "/"
})
})
}
In here the if ('serviceWorker' in navigator) will check if our browser supports service worker.
If it does, we're going to register our service worker on pageload. However the service is not always re-install itself unless we specificly update it.
Open the chrome tab, we should see the service worker with the scope for that URL:

[!note]
The first time the user visit the website, there will be no service worker. Even when the service worker becomes activated, it won't work until next reload.Also service worker works based on the scope. The scope is determined by its location on the server. For example the service worker is placed at
/subdir/index.html, then its scope is/subdir