Introduction | Service Workers

Features#

  • They cannot directly access to DOM
  • Programmable network proxy
  • Terminated when not being used
  • Make use of promises
  • Require HTTPS unless on localhost

Use Cases#

  • Caching assets & API calls
  • Push notification
  • Background data sync/preload
  • Used in PWA

Lifecycle#

Register -> Install -> Activate

Events#

install activate fetch push sync

Registering#

// main.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('./serviceworker.js')
.then(reg => {
console.log('registered successfully')
})
.catch(err => console.log(err))
})
}
// serviceWorker.js
self.addEventListener('install', e => {
console.log('Service worker installed')
})
self.addEventListener('activate', e => {
console.log('Service worker activated')
})