service-worker not working offline

Viewed 7118

I have successfully registered service-workers.js with no errors, and it has all the files required to work offline stored in cache. However, When i try to check if it'll respond 200 when offline, It fails!

Here is the code:

//Delete Old Cache
caches.delete('[v0.1.0]');

//Latest CACHE_NAME
var CACHE_NAME = '[v0.1.1] Portfolio (ATB00ker)';

//Files to be Cached
var urlsToCache = [
    '../../../index.html',
    '../jquery-3.2.1.slim.min.js',
    '../owl.carousel.min.js',
    '../scrollreveal.min.js',
    '../../images/bg-creator.webp',
    '../../images/icon/facebook.svg',
    '../../images/icon/telegram.svg',
    '../../images/icon/gmail.svg',
    '../../images/icon/github.webp'
];


self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        return cache.addAll(urlsToCache);
      })
  );
});


self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request, {ignoreSearch:true}).then(response => {
      return response || fetch(event.request);
    })
  );
});
4 Answers

You have /index.html cached offline but you are visiting / to test it. Those are two different paths and you will have to cache offline the one you want to visit.

The Problem in my case was that i had put the service-worker.js in "assets/js/user", when i moved it to root directory "/" it worked!

It seems that you didn't cater for offline. You have to direct the service worker to the offline page you want to display. Here is a snippet of code:

self.addEventListener('fetch', function (event) {
    console.log('Handling fetch event for', event.request.url);

    event.respondWith(            
        caches.match(event.request).then(function (response) {
            if (response) {
                console.log('Found response in cache:', response);

                return response;
            }

            console.log('No response found in cache. About to fetch from network...');

            return fetch(event.request).then(function (response) {
                console.log('Response from network is:', response);

                return response;
            }).catch(function (error) {                    
                console.error('Fetching failed:', error);

                return caches.match(OFFLINE_URL);
            });
        })
    );
});

Alternatively, you can have a look at this.

you must checklist "update on reload" enter image description here

Related