在service worker的HTML文件旁边添加图片和CSS文件,用于离线缓存

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

本文关键字:文件 CSS 缓存 离线 用于 添加 worker service HTML      更新时间:2023-09-26

我有这个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);
      })
    );
  }

});

这是标准的离线缓存服务worker: https://googlechrome.github.io/samples/service-worker/custom-offline-page/

如何缓存图像和CSS文件?现在,我用内联CSS创建了一个离线页面,并将图像转换为SVG代码。这并不理想。

我需要为离线缓存的图像使用不同id的多个服务工作者吗?

或者我可以为多个元素使用一个service worker进行离线缓存吗?

缓存可以存储多个请求,因此您可以多次调用cache.put(),您可以这样写:

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);
      });
    }));
  }))
};

或者,类似且更短,使用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);
  }))
};

你可以在Service Worker Cookbook中找到一个从外部资源加载资产集的例子。