【问题标题】:Service Worker not caching API content on first loadService Worker 未在首次加载时缓存 API 内容
【发布时间】:2016-06-27 07:43:57
【问题描述】:

我创建了一个启用服务工作者的应用程序,该应用程序旨在缓存来自 AJAX 调用的响应,以便离线查看。我遇到的问题是服务工作者缓存页面,而不是第一次加载时的 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。

任何帮助将不胜感激。

【问题讨论】:

    标签: polymer service-worker


    【解决方案1】:

    虽然skip-waiting + clients-claim 属性应该让您的服务工作者尽快获得控制权,但它仍然是一个异步过程,可能要等到您发出 AJAX 请求后才会启动。如果您想保证服务工作者将控制页面,那么您需要延迟您的 AJAX 请求,直到服务工作者获得控制权(例如,this technique),或者,您可以使用reload-on-install attribute

    同样重要的是,确保您的 &lt;platinum-sw-import-script&gt;&lt;platinum-sw-fetch&gt; 元素是您的 &lt;platinum-sw-register&gt; 元素的子元素,否则它们不会产生预期的效果。这在documentation 中被提及,但不幸的是,这只是运行时的静默失败。

    【讨论】:

    • 使用 reload-on-install 就像一个魅力。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2019-12-11
    • 2017-12-26
    相关资源
    最近更新 更多