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

时间:2016-06-27 07:43:58

标签: polymer service-worker

我已经创建了一个支持服务工作者的应用程序,用于缓存来自AJAX调用的响应,以便它可以脱机查看。我遇到的问题是服务工作者在第一次加载时缓存页面,而不是AJAX响应。

如果您访问http://ivesjames.github.io/pwa并在SW吐司后切换到飞行模式,则表示没有API内容。如果您重新上线并加载页面并再次执行此操作,则会在第二次加载时离线加载API内容。

我正在使用它来缓存API响应(通过Polymer docs获取):

(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。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

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

同样重要的是,确保您的<platinum-sw-import-script><platinum-sw-fetch>元素是您的<platinum-sw-register>元素的子元素,否则它们将无法达到预期的效果。这在documentation中被调用,但遗憾的是它只是在运行时出现了静默失败。