我创建了一个启用了Service Worker的应用程序,该应用程序旨在缓存来自AJAX调用的响应,以便可以脱机查看。我遇到的问题是服务工作者会缓存页面,但第一次加载页面时不会缓存AJAX响应。
如果您访问http://ivesjames.github.io/pwa并在SW祝酒后切换到飞行模式,则该API将不会显示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请求之后才能启动。如果要保证服务人员可以控制页面,那么您需要将AJAX请求延迟到服务人员获得控制权之后(例如,采用这种方法),或者可以使用的reload-on-install
属性。
同样重要的是,请确保您的<platinum-sw-import-script>
和<platinum-sw-fetch>
元素是您元素的子<platinum-sw-register>
元素,否则它们将不会达到预期的效果。这在文档中已提及,但不幸的是,这只是运行时的无提示故障。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句