【问题标题】:Adding images and CSS files ALONGSIDE HTML file in service worker for offline caching在 service worker 中添加图像和 CSS 文件以及 HTML 文件以进行离线缓存
【发布时间】:2016-06-27 08:54:01
【问题描述】:

我有这个服务人员:

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


});

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

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

我是否需要多个具有不同 ID 的 Service Worker 用于离线缓存图像?

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

【问题讨论】:

    标签: javascript google-chrome caching service-worker


    【解决方案1】:

    缓存可以存储多个请求,所以你可以多次调用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 中找到从外部资源加载资产集的示例。

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 1970-01-01
      • 2023-01-19
      • 2016-10-28
      • 2017-05-18
      • 2015-06-09
      • 2011-11-21
      • 2019-01-10
      相关资源
      最近更新 更多