Service Worker 在第一次加载时不缓存 API 内容

Service Worker not caching API content on first load

我创建了一个启用服务工作者的应用程序,旨在缓存来自 AJAX 调用的响应,以便可以离线查看。我 运行 遇到的问题是 service worker 缓存页面,而不是 AJAX 第一次加载时的响应。

如果您访问 http://ivesjames.github.io/pwa 并在 SW toast 后切换到飞行模式,它不会显示 API 内容。如果您重新联机并加载页面并再次执行此操作,它将在第二次加载时离线加载 API 内容。

这就是我用来缓存 API 响应的内容(取自 Polymer 文档):

(function(global) {

  global.untappdFetchHandler = function(request) {
    // Attempt to fetch(request). This will always make a network request, and will include the
    // full request URL, including the search parameters.
    return global.fetch(request).then(function(response) {
      if (response.ok) {
        // If we got back a successful response, great!
        return global.caches.open(global.toolbox.options.cacheName).then(function(cache) {
          // First, store the response in the cache, stripping away the search parameters to
          // normalize the URL key.
          return cache.put(stripSearchParameters(request.url), response.clone()).then(function() {
            // Once that entry is written to the cache, return the response to the controlled page.
            return response;
          });
        });
      }

      // If we got back an error response, raise a new Error, which will trigger the catch().
      throw new Error('A response with an error status code was returned.');
    }).catch(function(error) {
      // This code is executed when there's either a network error or a response with an error
      // status code was returned.
      return global.caches.open(global.toolbox.options.cacheName).then(function(cache) {
        // Normalize the request URL by stripping the search parameters, and then return a
        // previously cached response as a fallback.
        return cache.match(stripSearchParameters(request.url));
      });
    });
  }
})(self);

然后我在 sw-import 中定义处理程序:

  <platinum-sw-import-script href="scripts/untappd-fetch-handler.js">

  <platinum-sw-fetch handler="untappdFetchHandler"
                     path="/v4/user/checkins/jimouk?client_id=(apikey)&client_secret=(clientsecret)"
                     origin="https://api.untappd.com">
  </platinum-sw-fetch>

    <paper-toast id="caching-complete"
                 duration="6000"
                 text="Caching complete! This app will work offline.">
    </paper-toast>

    <platinum-sw-register auto-register
                          clients-claim
                          skip-waiting
                          base-uri="bower_components/platinum-sw/bootstrap"
                          on-service-worker-installed="displayInstalledToast">
      <platinum-sw-cache default-cache-strategy="fastest"
                         cache-config-file="cache-config.json">
      </platinum-sw-cache>
    </platinum-sw-register>

我哪里出错了吗?我不太确定为什么它适用于负载 #2 而不是负载 #1。

如有任何帮助,我们将不胜感激。

虽然 skip-waiting + clients-claim 属性应该使您的服务工作者尽快取得控制权,但它仍然是一个异步过程,可能要等到您的 AJAX 之后才会启动提出要求。如果你想保证 service worker 将控制页面,那么你需要延迟 AJAX 请求,直到 service worker 取得控制权(如下,例如 this technique), or alternatively, you can use the reload-on-install attribute

不过,同样重要的是,请确保您的 <platinum-sw-import-script><platinum-sw-fetch> 元素是 <platinum-sw-register> 元素的子元素,否则它们将不会产生预期的效果。这在 documentation 中被调用,但不幸的是,它只是运行时的静默失败。