Service Worker save App: Event handler of ‘install’ event must be added on the initial evaluation of worker script

Total
6
Shares

The app is not able to download. In Lighthouse I got the issue that the service worker or manifest fails.

I get two warnings, I do not understand :

  1. Event handler of install event must be added on the initial evaluation of worker script.
  2. Event handler of fetch event must be added on the initial evaluation of worker script.

App URLS: @Vimal Patel

Site: https://www.kuehroint.com/archenkanzel/archenkanzel-wimbachbruecke.html
Service Worker .sw https://www.kuehroint.com/archenkanzel/sw.js (Warnings)
Manifest Jason https://www.kuehroint.com/archenkanzel/manifest.json

This script i think is not in use.
https://www.kuehroint.com/archenkanzel/service-worker.js

Console Warnings in Code Comments :

self.addEventListener('install', function(event) {
 // Perform install steps
 var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = ['archenkanzel-wimbachbruecke.html'    ,
'     ../xcss/bergtouren.css',
'../icons/kuehr.jpg' 

];

 
self.addEventListener('install', function(event) {  /*<-- Event handler of 'install' event must be added on the initial evaluation of worker script */
 // Perform install steps
 event.waitUntil(
   caches.open(CACHE_NAME)
     .then(function(cache) {
       console.log('Opened cache');
       return cache.addAll(urlsToCache);
     })
 );
});

self.addEventListener('fetch', function(event) { /*<-- Event handler of 'fetch' event must be added on the initial evaluation of worker script.*/
 event.respondWith(
   caches.match(event.request)
     .then(function(response) {
       // Cache hit - return response
       if (response) {
         return response;
       }
       return fetch(event.request);
     }
   )
 );
});
});

Solution

Currently your service worker is not installed properly. Below are the few issue in your service worker Link

  • You have declared "install" event multiple times.
  • The first "install" event function is not properly closed. It is closed at the end. This is not valid javascript.

Solution:-

  • Remove your first install event (on line number 2).
  • Make sure your service worker functions are valid javascript functions.

Also make sure every file you add in your cache list should return a 200 response otherwise your install event will fail.

Leave a Reply

Your email address will not be published. Required fields are marked *