2016-03-05 43 views
1

我正嘗試使用服務工作者構建一個離線應用程序。我定義了諸如忽略服務工作者請求中的查詢參數

var urlsToPrefetch = ['foo.html', 'bar.js']

查詢字符串被添加到許多URL的資源列表,並導致該服務人員的fetch事件失敗,因爲該請求不匹配的高速緩存中的定義。查詢字符串主要用於強制獲取新文件版本。例如,請求bar.js作爲bar.js?version=2

有一個選項可以忽略查詢字符串(ignoreSearch下面),儘管從Chrome V50開始尚未實施。 Chrome Canary版僅適用於Win/Mac的

下面的代碼是在fetch eventListener

event.respondWith(
    // caches.match() will look for a cache entry in all of the caches available to the service worker. 
    // It's an alternative to first opening a specific named cache and then matching on that. 

    caches.match(event.request, {'ignoreSearch': true}).then(function(response) { 
     if (response) { 

      return response; 
     } 

     ... 
) 

回答

-1

使用Request代替:

var requestsToCache = [ 
    new Request('foo.html'), 
    new Request('bar.js') 
]; 
// ... 
    cache.addAll(requestsToCache); 
// ... 
+0

這隻適用於如果你想要緩存一切安裝。 – Marco

2

您可以創建一個新的要求,移除查詢字符串,然後用它代替原來的:

var url = new URL(request.url); 
url.search = ''; 
url.fragment = ''; 

let cleanRequest = new Request(url, { 
    method: request.method, 
    headers: request.headers, 
    mode: request.mode, 
    credentials: request.credentials, 
    cache: request.cache, 
    redirect: request.redirect, 
    referrer: request.referrer, 
    integrity: request.integrity, 
}); 
+0

如果您只傳遞一個URL字符串,將會自動創建Request。請參閱https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-matchall-method的5.4.2.3.3也不需要複製所有其他'Request'屬性,因爲只有URL對Cache Storage API很重要。 –

+0

是的,如果您只需要使用緩存,實際上會更好,因爲如果「引用者」是一個跨源URL,「Request」構造函數可能會拋出。 – Marco