新资产的服务工人部队更新 [英] Service-worker force update of new assets

查看:52
本文介绍了新资产的服务工人部队更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been reading through the html5rocks Introduction to service worker article and have created a basic service worker that caches the page, JS and CSS which works as expected:

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 进行更改时,由于 Service Worker 正确地从缓存中返回了 CSS,因此未采用此更改.

When I make a change to the CSS, this change is not being picked up as the service worker is correctly returning the CSS from the cache.

我遇到的问题是,如果我要更改 HTML、JS 或 CSS,我将如何确保服务工作者从服务器加载较新版本,而不是从缓存加载?我试过在 CSS 导入中使用版本戳,但似乎没有用.

Where I'm stuck is if I were to change the HTML, JS or CSS, how would I make sure that the service-worker loads the newer version from the server if it can rather than from the cache? I've tried using version stamps on the CSS import but that didn't seem to work.

推荐答案

一种选择只是使用 service worker 的缓存作为后备,并且总是尝试去 网络优先 通过 fetch().但是,缓存优先策略提供的一些性能提升会有所损失.

One option is just to use a the service worker's cache as a fallback, and always attempt to go network-first via a fetch(). You lose some performance gains that a cache-first strategy offers, though.

另一种方法是使用 sw-precache 生成您的 Service Worker 脚本作为您网站构建过程的一部分.

An alternative approach would be to use sw-precache to generate your service worker script as part of your site's build process.

它生成的 Service Worker 将使用文件内容的哈希值来检测更改,并在部署新版本时自动更新缓存.它还将使用缓存破坏 URL 查询参数来确保您不会意外地使用 HTTP 缓存中的过时版本填充 Service Worker 缓存.

The service worker that it generates will use a hash of the file's contents to detect changes, and automatically update the cache when a new version is deployed. It will also use a cache-busting URL query parameter to ensure that you don't accidentally populate your service worker cache with an out-of-date version from the HTTP cache.

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

In practice, you'll end up with a service worker that uses a performance-friendly cache-first strategy, but the cache will get updated "in the background" after the page loads so that the next time it's visited, everything is fresh. If you want, it's possible to display a message to the user letting them know that there's updated content available and prompting them to reload.

这篇关于新资产的服务工人部队更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆