0
votes

I'm new to PWA and i'm training on a simple project. After the first run on goole chrome, for which everything worked fine, I changed the cacheName const in the service worker and the title in the index.html to test the re-caching of all site assets. From here on the cache still creates but it is empty and i get the error "Uncaught (in promise) TypeError: Request failed" referred to the line of SW we const staticCacheName = 'site-static-v1' is declared.

Here the code of SW:

const staticCacheName = 'site-static-v2';
const assets = [
    './',
    './index.html',
    './index.js',
    './main.js',
    './style.css',
    'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css',
    'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js',
    'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js',
    'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];

// install service worker
self.addEventListener('install', evt => {
    console.log('service worker has been installed');
    evt.waitUntil( 
        caches.open(staticCacheName).then(cache => {
            console.log('caching shell assets');
            cache.addAll(assets);
        })
    );
   
});

// activate event
self.addEventListener('activate', evt => {
    console.log('service worker has been activated');
});

// fetch event
self.addEventListener('fetch', evt => {
    evt.respondWith(
        caches.match(evt.request).then(cacheRes => {
            return cacheRes || fetch(evt.request);
        })
    );
});

Any help will be greatly appreciated.

1
most likely one of the files you are trying to pre-cached is not resolving, ie 404. Add a .catch to your addAll call to see if you can figure out which one. hint, if any of the URLs fail in addAll then they all fail. That is why I stopped usiing it a while back and started using cache.put in a loop. - Chris Love

1 Answers

0
votes

The problem is in your assets array. It only takes URLpath to the file to be cached not the filepath. In nutshell remove the dots from the front of these paths.

const assets = [
    '/',
    '/index.html',
    '/index.js',
    '/main.js',
    '/style.css',
    'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css',
    'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js',
    'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js',
    'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];

And if you are storing the js and css files in a static folder with /static as the route then you need to add /static in front of each file which is present in it.

Again i want to mention that it only takes the URLpath not the FILEpath. It has nothing to take with your filepath. The main reason is actually it caches the assets from the server not from your computer. Thus it needs a route not a Filepath.