服务工作者强制更新新资产

时间:2015-10-21 14:43:27

标签: service-worker

我一直在阅读html5rocks Introduction to service worker文章并创建了一个基本的服务工作者来缓存页面,JS和CSS按预期工作:

var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  '/'
];

// Set the callback for the install step
self.addEventListener('install', function (event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('fetch', function (event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }

        // IMPORTANT: Clone the request. A request is a stream and
        // can only be consumed once. Since we are consuming this
        // once by cache and once by the browser for fetch, we need
        // to clone the response
        var fetchRequest = event.request.clone();

        return fetch(fetchRequest).then(
          function(response) {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have 2 stream.
            var responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(function(cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
    );
});

当我对CSS进行更改时,由于服务工作者正在从缓存中正确返回CSS,因此未进行此更改。

如果我要更改HTML,JS或CSS,我将如何确保服务工作者从服务器加载新版本(如果可以)而不是从缓存中加载?我尝试在CSS导入上使用版本标记,但似乎没有用。

5 个答案:

答案 0 :(得分:38)

一种选择就是使用服务工作者的缓存作为后备,并始终尝试通过fetch()转到network-first。但是,您会失去缓存优先策略所带来的性能提升。

另一种方法是使用sw-precache生成服务工作者脚本,作为网站构建过程的一部分。

它生成的服务工作者将使用文件内容的散列来检测更改,并在部署新版本时自动更新缓存。它还将使用缓存清除URL查询参数来确保您不会意外地使用HTTP缓存中的过时版本填充服务工作缓存。

在实践中,您最终会得到一个使用性能友好的缓存优先策略的服务工作者,但是在页面加载后缓存将在“后台”更新,以便下次访问时,所有内容很新鲜如果你愿意,它是possible to display a message给用户,让他们知道有更新的内容可用,并提示他们重新加载。

答案 1 :(得分:19)

使缓存无效的一种方法是在缓存文件中的任何内容时更改CACHE_NAME的版本。由于该更改将更改,service-worker.js浏览器将加载更新版本,您将有机会删除旧缓存并创建新缓存。您可以删除activate处理程序中的旧缓存。这是prefetch sample中描述的策略。 如果您已经在CSS文件上使用某种版本标记,请确保它们找到进入服务工作者脚本的方式。

这当然不会改变CSS文件上的缓存头需要正确设置的事实。否则,服务工作人员只会加载已经缓存在浏览器缓存中的文件。

答案 2 :(得分:1)

浏览器缓存问题

这里的主要问题是,当您安装新的服务工作者时,他会获取由先前的服务工作者处理的请求,并且很有可能他从缓存中获取资源,因为这是您的缓存策略。然后,即使您正在使用新代码,新的缓存名称(称为self.skipWaiting())更新服务工作者,他仍会在缓存中放入旧资源!

这就是我全面更新Service Worker的方式

一件事是,服务人员将在每次代码脚本更改时触发 install 事件,因此您无需使用版本标记或其他任何东西,只需保持相同的文件名即可可以,甚至推荐。 There are other ways the browser will consider your service worker updated.

1。重写您的 install 事件处理程序

我不使用cache.addAll,因为它已损坏。的确,如果无法获取要缓存的资源中的只有一个,则整个安装将失败,甚至没有一个文件将被添加到缓存中。现在,假设要从存储桶中自动生成要缓存的文件列表(这是我的情况),然后更新存储桶并删除一个文件,那么PWA将安装失败,并且应该不会。

sw.js

self.addEventListener('install', (event) => {
  // prevents the waiting, meaning the service worker activates
  // as soon as it's finished installing
  // NOTE: don't use this if you don't want your sw to control pages
  // that were loaded with an older version
  self.skipWaiting();

  event.waitUntil((async () => {
    try {
      // self.cacheName and self.contentToCache are imported via a script
      const cache = await caches.open(self.cacheName);
      const total = self.contentToCache.length;
      let installed = 0;

      await Promise.all(self.contentToCache.map(async (url) => {
        let controller;

        try {
          controller = new AbortController();
          const { signal } = controller;
          // the cache option set to reload will force the browser to
          // request any of these resources via the network,
          // which avoids caching older files again
          const req = new Request(url, { cache: 'reload' });
          const res = await fetch(req, { signal });

          if (res && res.status === 200) {
            await cache.put(req, res.clone());
            installed += 1;
          } else {
            console.info(`unable to fetch ${url} (${res.status})`);
          }
        } catch (e) {
          console.info(`unable to fetch ${url}, ${e.message}`);
          // abort request in any case
          controller.abort();
        }
      }));

      if (installed === total) {
        console.info(`application successfully installed (${installed}/${total} files added in cache)`);
      } else {
        console.info(`application partially installed (${installed}/${total} files added in cache)`);
      }
    } catch (e) {
      console.error(`unable to install application, ${e.message}`);
    }
  })());
});

2。激活(新)服务工作者后,请清理旧的缓存:

sw.js

// remove old cache if any
self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    const cacheNames = await caches.keys();

    await Promise.all(cacheNames.map(async (cacheName) => {
      if (self.cacheName !== cacheName) {
        await caches.delete(cacheName);
      }
    }));
  })());
});

3。每次更新资产时,我都会更新缓存名称:

sw.js

// this imported script has the newly generated cache name (self.cacheName)
// and a list of all the files on my bucket I want to be cached (self.contentToCache),
// and is automatically generated in Gitlab based on the tag version
self.importScripts('cache.js');

// the install event will be triggered if there's any update,
// a new cache will be created (see 1.) and the old one deleted (see 2.)

4。处理缓存中的ExpiresCache-Control响应标头

我在服务工作者的 fetch 事件处理程序中使用这些标头,以捕获在资源过期/应刷新时是否应通过网络请求资源。

基本示例:

// ...

try {
  const cachedResponse = await caches.match(event.request);

  if (exists(cachedResponse)) {
    const expiredDate = new Date(cachedResponse.headers.get('Expires'));

    if (expiredDate.toString() !== 'Invalid Date' && new Date() <= expiredDate) {
      return cachedResponse.clone();
    }
  }

  // expired or not in cache, request via network...
} catch (e) {
  // do something...
}
// ...

答案 3 :(得分:0)

对我来说最简单:

const cacheName = 'my-app-v1';

self.addEventListener('activate', async (event) => {

    const existingCaches = await caches.keys();
    const invalidCaches = existingCaches.filter(c => c !== cacheName);
    await Promise.all(invalidCaches.map(ic => caches.delete(ic)));

    // do whatever else you need to...

});

如果您有多个缓存,您可以修改代码以使其具有选择性。

答案 4 :(得分:0)

在我的主页中,我使用一些 PHP 从 mySQL 中获取数据。

为了让 php 数据在您有互联网时始终保持新鲜,我使用以毫秒为单位的日期作为我的服务工作者的版本。

在这种情况下,当您有互联网并重新加载页面时,兑现页面将始终更新。

//SET VERSION
const version = Date.now();
const staticCacheName = version + 'staticfiles';

//INSTALL
self.addEventListener('install', function(e) {
    e.waitUntil(
        caches.open(staticCacheName).then(function(cache) {
            return cache.addAll([
相关问题