Search code examples
javascripthtmlservice-workeroffline-caching

Show offline cache when server is unreachable


Is it possible to show an offline cache of my website when the server is down?

All the examples I can find regarding offline pages has to do with the client being offline. What I need is to show the user a cached version of my site if the server can't be reached.

I've read about the Cache Manifest in HMTL 5 but it's getting removed and it causes to many problems.

What can be done without using any other loadbalancing servers and such?


Solution

  • I recently learned that with Fetch API and service workers its dead simple:

    First, you register the Service worker:

      if (!navigator.serviceWorker) return;
    
      navigator.serviceWorker.register('/sw.js')
    

    Then configure it to cache whats needed:

    self.addEventListener('install', function(event) {
      event.waitUntil(
        caches.open(staticCacheName).then(function(cache) {
          return cache.addAll([
            '/',
            'js/main.js',
            'css/main.css',
            'imgs/icon.png',      
          ]);
        })
      );
    });
    

    And use Fetch API to get cached peaces if no response from the call:

    self.addEventListener('fetch', function(event) {
      event.respondWith(
        caches.match(event.request).then(function(response) {
          return response || fetch(event.request);
        })
      );
    });
    

    if need to get cached version only if server is down, try something like:

    self.addEventListener('fetch', function(event) {
      event.respondWith(
        return fetch(event.request).then(function(response) {
         if (response.status !== 200) {        
           caches.match(event.request).then(function(response) {
             return response;
           }).catch(function(error) {
             console.error('Fetching failed:', error);
             throw error;
          });
        })
      );
    });
    

    p.s. using Fetch API seems much nicer way than implementing old and nasty XMLHttpRequest.