Chrome 54 中的 CacheQueryOptions Arrive

如果您在服務工作者中使用 Cache Storage API,或是透過 window.caches 直接從網路應用程式使用,那麼有個好消息:從 Chrome 54 開始,系統將支援完整的 CacheQueryOptions,讓您更輕鬆地找到所需的快取回應。

有哪些選項?

您可以在任何對 CacheStorage.match()Cache.match() 的呼叫中設定下列選項。如未設定,則預設為 false (cacheName 則為 undefined),您可以在單一 match() 呼叫中使用多個選項。

ignoreSearch

這會指示比對演算法忽略網址的「搜尋」部分,也就是網址查詢參數。如果來源網址含有用於 Analytics 追蹤等用途的查詢參數,但這些參數在快取中無法明確識別資源,這項功能就非常實用。舉例來說,許多人曾經遭遇下列服務工作站的「陷阱」:

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

ignoreMethodignoreVaryignoreSearchcacheName 更專門,但用途較為特定。

ignoreMethod 可讓您將 Request 物件傳入 match(),該物件包含任何 method (POSTPUT 等) 做為第一個參數。通常只允許 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

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