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

科迪(Cody Raspien)

我有这个服务人员:

'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的服务人员来处理图像以进行离线缓存?

还是可以将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中找到从外部资源加载资产集的示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

持久服务工作者和缓存 HTML 和 PNG 文件

服务工作者缓存文件但不离线加载

服务工作者将文件从API调用添加到预缓存

服务工作者不会从缓存中返回文件

服务工作者从磁盘缓存中缓存资源

服务工作者在反应中缓存的路由

服务工作者缓存与 VuexPersistence

通常,服务工作者应预缓存哪些文件?

Javascript服务工作者:从缓存中获取资源,但也进行更新

从create-react-app中的服务工作者缓存中排除index.html

未找到reactjs服务工作者.license文件

如何精确添加“允许服务工作者”以在上层文件夹中注册服务工作者范围

将版本/哈希添加到服务工作者文件后会发生什么?

将服务工作者添加到startup.cs文件

服务工作者不在离线工作

从main.js文件或index.html调用服务工作者是否正确?

服务工作者中的XMLHttpRequest

如何在Google Devtools中强制更新服务工作者文件?

离线时服务工作者未注册

“服务工作者”是否支持离线HTML表单数据?

服务工作者和客户端请求“缓存控制”:“无缓存”

在服务工作者中服务之前,可以编辑缓存的index.html吗?

WebView:以编程方式清除服务工作者缓存

PWA服务工作者缓存/更新预期行为

如何由服务工作者更新缓存的资源

具有SSL证书缓存的服务工作者

注销时如何清除服务工作者缓存?

如何防止服务工作者删除缓存,PWA

服务工作者缓存破坏谷歌地图 api