smithtimmytim/brightlycolored.org

View on GitHub
_includes/service-worker.html

Summary

Maintainability
Test Coverage
<script>
  function showOfflineToast() {
    let offlineToast = document.querySelector('.offline-ready');
    offlineToast.classList.add('active');
    setTimeout(function(){ 
      offlineToast.className = offlineToast.className.replace("active", "").trim();
    }, 5500);
  }

  if (navigator.serviceWorker) {
    navigator.serviceWorker.register('/sw.js').then(function(reg) {
        if (!reg.installing) return;
        console.log("[*] ServiceWorker is installing...");

        var worker = reg.installing;

        worker.addEventListener('statechange', function() {
            if (worker.state == 'redundant') {
                console.log('[*] Install failed');
            }
            if (worker.state == 'installed') {
                console.log('[*] Install successful!');
            }
            if (worker.state == 'activated' && !navigator.serviceWorker.controller) {
              showOfflineToast();
            }
        });
    });
  }
</script>