如果您的问题和相应的答案页面路由是基于约定的,您可以这样做。例如,question-1.html
回答为answer-1.html
。如果您遵循此或类似模式,您可以捕获传入请求并立即在后台question-1.html
启动请求。answer-1.html
self.addEventListener('fetch', function(event) {
// If url is a question url, initiate answer request and cache it
if(event.request.url.indexOf('question-') >= 0) {
// Generate the answer url and request by convention
var answerUrl = event.request.url.replace('question-', 'answer-');
var answerRequest = new Request(answerUrl);
// Initiate the fetch request for the answer page but don't wait on the response
fetch(answerRequest).then(function(answerResponse) {
// Cache the answer response when you get it
caches.open('answers').then(function(cache) {
cache.put(answerRequest, answerResponse);
});
});
// Return the question response
event.respondWith(fetch(event.request));
} else if(event.request.url.indexOf('answer-') >= 0) {
// If the request is for an answer, respond from cache
event.respondWith(caches.open('answers').then(function(cache) {
// Return the answer from cache (or network just in case)
return cache.match(event.request) || fetch(event.request);
});
}
});
上面的代码中可能有一些改进。例如,如果用户的回答速度足以击败回答页面的后台获取,他们可能不得不等待网络响应而不是使用缓存,但这不太可能。