Cody Raspien
Cody Raspien

Reputation: 1845

Adding images and CSS files ALONGSIDE HTML file in service worker for offline caching

I have this service worker:

'use strict';

const CACHE_VERSION = 1;
let CURRENT_CACHES = {
  offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'http://example.com/offline.html';

function createCacheBustedRequest(url) {
  let request = new Request(url, {cache: 'reload'});

  if ('cache' in request) {
    return request;
  }

  let bustedUrl = new URL(url, self.location.href);
  bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
  return new Request(bustedUrl);
}

self.addEventListener('install', event => {
  event.waitUntil(

    fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
      return caches.open(CURRENT_CACHES.offline).then(function(cache) {
        return cache.put(OFFLINE_URL, response);
      });
    })
  );
});

self.addEventListener('activate', event => {

  let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (expectedCacheNames.indexOf(cacheName) === -1) {

            console.log('Deleting out of date cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {

  if (event.request.mode === 'navigate' ||
      (event.request.method === 'GET' &&
       event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling fetch event for', event.request.url);
    event.respondWith(
      fetch(createCacheBustedRequest(event.request.url)).catch(error => {

        console.log('Fetch failed; returning offline page instead.', error);
        return caches.match(OFFLINE_URL);
      })
    );
  }


});

It's the standard service worker - 
This is my service worker:

'use strict';


const CACHE_VERSION = 1;
let CURRENT_CACHES = {
  offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'offline.html';

function createCacheBustedRequest(url) {
  let request = new Request(url, {cache: 'reload'});

  if ('cache' in request) {
    return request;
  }

  let bustedUrl = new URL(url, self.location.href);
  bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
  return new Request(bustedUrl);
}

self.addEventListener('install', event => {
  event.waitUntil(

    fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
      return caches.open(CURRENT_CACHES.offline).then(function(cache) {
        return cache.put(OFFLINE_URL, response);
      });
    })
  );
});

self.addEventListener('activate', event => {

  let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (expectedCacheNames.indexOf(cacheName) === -1) {

            console.log('Deleting out of date cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {

  if (event.request.mode === 'navigate' ||
      (event.request.method === 'GET' &&
       event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling fetch event for', event.request.url);
    event.respondWith(
      fetch(createCacheBustedRequest(event.request.url)).catch(error => {

        console.log('Fetch failed; returning offline page instead.', error);
        return caches.match(OFFLINE_URL);
      })
    );
  }


});

It's the standard offline cache service worker: https://googlechrome.github.io/samples/service-worker/custom-offline-page/

How do I cache images and CSS files? Right now, I create an offline page with in-line CSS and converted by images into SVG code. This is not ideal.

Do I need to have multiple service workers with different IDs for images for offline-caching?

Or can I use 1 service worker for multiple elements for offline caching?

Upvotes: 2

Views: 1640

Answers (1)

Salva
Salva

Reputation: 6855

Caches can store multiple requests so you can call cache.put() several times, you could write:

var ASSETS = ['/index.html', '/js/index.js', '/style/style.css'];

self.oninstall = function (evt) {
  evt.waitUntil(caches.open('offline-cache-name').then(function (cache) {
    return Promise.all(ASSETS.map(function (url) {
      return fetch(url).then(function (response) {
        return cache.put(url, response);
      });
    }));
  }))
};

Or, similarly and shorter, using addAll():

var ASSETS = ['/index.html', '/js/index.js', '/style/style.css'];

self.oninstall = function (evt) {
  evt.waitUntil(caches.open('offline-cache-name').then(function (cache) {
    return cache.addAll(ASSETS);
  }))
};

You can find an example loading the set of assets from an external resource in the Service Worker Cookbook.

Upvotes: 5

Related Questions