<repo_name>raviCHCopart/raviCHCopart.github.io<file_sep>/README.md
# serviceworkers.github.io
<file_sep>/sw.js
self.addEventListener('install', async e => {
  console.log('SW Installed!')
  const cache = await caches.open('pwa-static')
  cache.addAll(['./', './main.js'])
})
self.addEventListener('activate', e => {
  var cacheKeeplist = ['pwa-static']
  e.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(
        keyList.map(function(key) {
          if (cacheKeeplist.indexOf(key) === -1) {
            return caches.delete(key)
          }
        })
      )
    })
  )
})
self.addEventListener('fetch', e => {
  e.respondWith(
    (async function() {
      const cache = await caches.open('pwa-dynamic')
      const cachedResponse = await cache.match(e.request)
      if (cachedResponse) return cachedResponse
      const networkResponse = await fetch(e.request)
      e.waitUntil(cache.put(e.request, networkResponse.clone()))
      return networkResponse
    })()
  )
})
<file_sep>/main.js
window.onload = async () => {
  const network = document.querySelector('#network')
  const navigator = window.navigator
  const online = navigator.onLine
  if (online) {
    network.classList.add('badge-success')
    network.innerHTML = '<strong>Online ---- 😊</strong>'
  } else {
    network.classList.add('badge-danger')
    network.innerHTML = '<strong>Offline ---- 😭</strong>'
  }
  if ('serviceWorker' in navigator) {
    try {
      const swRegistration = await navigator.serviceWorker.register('sw.js')
      console.log('SW registred!')
    } catch (err) {
      console.log('SW reg failed!')
    }
  } else {
    console.log('SW not supported')
  }
  window.addEventListener('online', () => {
    network.classList.remove('badge-danger')
    network.classList.add('badge-success')
    network.innerHTML = '<strong>Online ---- 😊</strong>'
  })

  window.addEventListener('offline', () => {
    network.classList.remove('badge-success')
    network.classList.add('badge-danger')
    network.innerHTML = '<strong>Offline ---- 😭</strong>'
  })
}
