Chrome 54 中的 CacheQueryOptions Arrive

如果您在服務工作站內或直接透過 window.caches 在網頁應用程式中使用 Cache Storage API,好消息是:從 Chrome 54 版開始,我們支援完整的 CacheQueryOptions,更易於找到需要的快取回應。

有哪些選項?

您可以在任何對 CacheStorage.match()Cache.match() 的呼叫中設定下列選項。如未設定,這些參數都會預設為 false (cacheNameundefined),您可以在 match() 呼叫中使用多個選項。

ignoreSearch

這指示比對演算法忽略網址的「搜尋」部分 (又稱為網址查詢參數)。如果您的來源網址包含用於 Analytics (分析) 追蹤等特定查詢參數,但對快取中特定資源沒有特別意義,這個做法就很實用。例如,許多人已經落入以下服務人員「gotcha」:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-cache')
      .then(cache => cache.add('index.html'))
  );
});

self.addEventListener('fetch', event => {
  // Make sure this is a navigation request before responding.
  if (event.request.mode === 'navigation') {
    event.respondWith(
      caches.match(event.request) || fetch(event.request)
    );
  }
});

當使用者直接前往 index.html 時,這類程式碼可正常運作,但如果網頁應用程式透過分析供應商追蹤傳入連結,且使用者前往 index.html?utm_source=some-referral,該怎麼做?根據預設,將 index.html?utm_source=some-referral 傳遞至 caches.match() 不會傳回 index.html 的項目。但是,如果將 ignoreSearch 設為 true,則無論設定哪些查詢參數,您都可以擷取預期的快取回應:

caches.match(event.request, {ignoreSearch: true})

cacheName

如果您有多個快取,並希望回應儲存在單一特定快取中,cacheName 非常實用。使用這個方法可以提高查詢的效率 (因為瀏覽器只需檢查一個快取而非所有快取內部),並且可以讓您在有多個快取可能會將該網址做為金鑰時,擷取特定網址的特定回應。cacheName 只有在與 CacheStorage.match() 搭配使用時 (而非 Cache.match()) 才會產生作用,因為 Cache.match() 會在已命名的快取單一上執行。

// The following are functionally equivalent:
caches.open('my-cache')
  .then(cache => cache.match('index.html'));

// or...
caches.match('index.html', {cacheName: 'my-cache'});

ignoreMethodignoreVary

ignoreSearchcacheName 相比,ignoreMethodignoreVary 較小眾族群,但可用於特定用途。

ignoreMethod 可讓您將包含任何 method (POSTPUT 等) 的 Request 物件傳入 match()。通常只允許使用 GETHEAD 要求。

// In a more realistic scenario, postRequest might come from
// the request property of a FetchEvent.
const postRequest = new Request('index.html', {method: 'post'});

// This will never match anything.
caches.match(postRequest);

// This will match index.html in any cache.
caches.match(postRequest, {ignoreMethod: true});

如果設為 trueignoreVary 表示系統會執行快取查詢,不會考慮快取回應中設定的任何 Vary 標頭。如果您知道不處理使用 Vary 標頭的快取回應,就不必擔心設定此選項的問題。

瀏覽器支援

CacheQueryOptions 只適用於支援 Cache Storage API 的瀏覽器。除了 Chrome 和 Chromium 瀏覽器之外,目前僅支援 Firefox,已內建支援 CacheQueryOptions 的 Firefox。

如果開發人員想在 Chrome 54 之前的版本中使用 CacheQueryOptions,可以使用 polyfill (由 Arthur Stolyar 提供)。