在 Service Worker 中添加图像和 CSS 文件以及 HTML 文件以进行离线缓存

Cod*_*ien 2 javascript caching google-chrome 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);
      })
    );
  }


});
Run Code Online (Sandbox Code Playgroud)

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

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

我是否需要有多个具有不同 ID 的服务工作人员来存储图像以进行离线缓存?

或者我可以使用 1 个服务工作线程来处理多个元素以进行离线缓存吗?

Sal*_*lva 5

缓存可以存储多个请求,因此您可以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);
      });
    }));
  }))
};
Run Code Online (Sandbox Code Playgroud)

或者,类似且更短,使用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);
  }))
};
Run Code Online (Sandbox Code Playgroud)

您可以在Service Worker Cookbook中找到从外部资源加载资产集的示例。