简体   繁体   English

在服务工作者中添加图像和CSS文件以及HTML文件以进行离线缓存

[英]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/ 它是标准的离线缓存服务工作者: https : //googlechrome.github.io/samples/service-worker/custom-offline-page/

How do I cache images and CSS files? 如何缓存图像和CSS文件? Right now, I create an offline page with in-line CSS and converted by images into SVG code. 现在,我使用嵌入式CSS创建一个脱机页面,然后将图像转换为SVG代码。 This is not ideal. 这是不理想的。

Do I need to have multiple service workers with different IDs for images for offline-caching? 我是否需要多个具有不同ID的服务人员来处理图像以进行离线缓存?

Or can I use 1 service worker for multiple elements for offline caching? 还是可以将1个服务工作者用于多个元素以进行离线缓存?

Caches can store multiple requests so you can call cache.put() several times, you could write: 缓存可以存储多个请求,因此您可以多次调用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);
      });
    }));
  }))
};

Or, similarly and shorter, using addAll() : 或者,使用addAll()类似地并且更短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 . 您可以在Service Worker Cookbook中找到从外部资源加载资产集的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM