【发布时间】: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。
任何帮助将不胜感激。
【问题讨论】: