客户端存储CacheStorage

2020-09-30  本文已影响0人  戴眼镜的松鼠

缓存数据的大小

StorageEstimate

if(navigator.storage && navigator.storage.estimate) {
  navigator.storage.estimate().then(estimate => {
    // 原始的单位是byte. 转成MB
    const ut = 1024 * 1024;
    return ({
      total: estimate.quota / ut,
      usage: estimate.usage / ut
    });
  });
};

一个域可以有多个命名 Cache 对象

CacheStorage Api

1. CacheStorage.open(cacheName)

  // 示例
  const cacheName = 'test-cache-name'
  caches.open(cacheName).then(cache => {
    // cache 对象
    console.log('cache.....', cache);
  })

2. CacheStorage.match(request, options)

  // 示例 url
  const notExistUrl = '/api'
  caches.match(notExistUrl).then(res => {
    console.log(res) // undefined
  })
  const existUrl = '/index.js'
  caches.match(existUrl).then(res => {
    console.log(res) // Response
  })
  // Request 对象
  const req = new Request('http://localhost:8008/api/ws', {
    method: 'get',
  })
  caches.match(req).then(res => {
    return res.json()
  }).then(r => {
    console.log(r); // {a: 1, b: 2}
  })

ignoreSearch: [Boolean] 指定匹配过程是否应该忽略url中查询参数。举个例子,如果该参数设置为true, 那么 ?value=bar 作为 http://foo.com/?value=bar 中的查询参数将会在匹配过程中被忽略。该参数默认 false。

  const existUrlAndQuery = '/index.js?a=1'
  caches.match(existUrlAndQuery).then(res=>
  {
    console.log(res) // undefined
  })
  caches.match(existUrlAndQuery, {
    ignoreSearch: true
  }).then(res => {
    console.log(res) // Response
  })

ignoreMethod: [Boolean] 当被设置为 true 时,将会阻止在匹配操作中对 Request请求的 http 方式的验证 (通常只允许 GET 和 HEAD 两种请求方式)。该参数默认为 false。

// POST请求不允许缓存。

// 报错 cache.js:13 Uncaught (in promise) TypeError: Failed to execute 'add' on 'Cache': Add/AddAll only supports the GET request method.

  const req = new Request(
    'http://localhost:8008/api/ws', {
      method: 'head', // post, get, head都一样被忽略
      mode: 'cors',
    })
  caches.match(req, {
    cacheName: 'test-cache-name',
    ignoreMethod: true
  }).then(res => {
    return res.json()
  }).then(r => {
    console.log(r); // {a: 1, b: 2}
  })

ignoreVary: [Boolean] 当该字段被设置为 true, 告知在匹配操作中忽略对VARY头信息的匹配。换句话说,当请求 URL 匹配上,你将获取匹配的 Response 对象,无论请求的 VARY 头存在或者没有。该参数默认为 false。

  // 没理解
  const req = new Request('http://localhost:8008/api/ws', {
    method: 'get',
    mode: 'cors',
    vary: 'User-Agent'
  })
  caches.match(req, {
    cacheName: 'test-cache-name',
    ignoreVary: false
  }).then(res => {
    return res.json()
  }).then(r => {
    console.log(r); // {a: 1, b: 2}
  })

cacheName: [DOMString] 表示所要搜索的缓存名称.

[图片上传失败...(image-d67305-1601447981344)]
[图片上传失败...(image-28bf4e-1601447981345)]

// 指定cacheName
const cacheName = 'test-cache-name';
caches.match('/cache.js', {
  cacheName
}).then(res => {
  return res.text()
}).then(r => {
  console.log(r);
})

3. CacheStorage.has(cacheName)

  // 存在 cacheName
  caches.has('test-cache-name').then((res) => {
    console.log(res) // true
  });
  // 不存在 cacheName
  caches.has('test-cache-name-not').then((res) => {
    console.log(res) // false
  });

4. CacheStorage.delete(cacheName)

  const testDeleteCacheName = 'test-delete-cache-name'
  caches.open(testDeleteCacheName).then(r => {
    // 删除test-delete-cache-name
    caches.delete(testDeleteCacheName).then((res) => {
      console.log(res); // true
    });
    // 删除不存在的test-cache-name-not
    caches.delete('test-cache-name-not').then((res) => {
      console.log(res); // false
    });
  })

5. CacheStorage.keys()

  // 按创建顺序
  caches.keys().then(res => {
    console.log(res);
    //我本地的["my-test-cache-v1", "workbox-runtime-http://127.0.0.1:5500/", "test-cache-name"]
  })

Cache Api

  // 示例
  const cacheName = 'test-cache-name'
  caches.open(cacheName).then(cache => {
    // cache对象就是cacheName为'test-cache-name'的cache对象
    console.log('cache.....', cache);
  })

1. cache.match(request, options)

  // 存在
  const req1 = new Request('http://localhost:8008/api/ws', {
    method: 'get',
    mode: 'cors',
  })
  const notExistUrl = 'not-exist-url'
  caches.open('test-cache-name').then(cache => {
    cache.match(req1,).then(r => {
      console.log(r); // Response
    })
    cache.match(notExistUrl,).then(r => {
      console.log(r); // undefined
    })
  })

2. cache.matchAll(request, options)

  cache.matchAll().then(res => {
    console.log(res) // [Response, Response, Response]
  })

3. cache.add(request)

  // cache.add方法等同于下面,默认发起一个fetch请求
  fetch(url).then(function (response) {
    if (!response.ok) {
      throw new TypeError('bad response status');
    }
    return cache.put(url, response);
  })
  const req = new Request('http://localhost:8008/v3/test-6', {
    method: 'get'
  })
  caches.open('test-cache-name').then(cache => {
    cache.add('style.css').then(res => {
      console.log('style.css....', res);
    })
    // 无需发起fetch请求,默认发起,将请求结果缓存。
    cache.add(req).then(res => {
      console.log('add....req....', res);
    })
  })

4. cache.addAll(requests)

  const req1 = new Request('http://localhost:8008/v3/test-1', {
    method: 'get'
  })
  const req2 = new Request('http://localhost:8008/v3/test-2', {
    method: 'get'
  })
  const req3 = new Request('http://localhost:8008/v3/test-3', {
    method: 'get'
  })
  caches.open('test-cache-name').then(cache => {
    cache.addAll([
      req1,
      req2,
      req3,
      'style.css'
    ]).then(res => {
      console.log('add....req....', res);
    })
  })

5. cache.delete(request,{options})

ignoreSearch: 一个 Boolean 值,指定匹配进程中是否忽略url中的查询字符串。如果设置为true,http://foo.com/?value=bar 中的 ?value=bar 部分在执行匹配时会被忽略。默认为false。
ignoreMethod: 一个 Boolean 值,当设置为true时,将阻止匹配操作验证{domxref("Request")}} HTTP方法(通常只允许GET和HEAD)。默认为false。
ignoreVary: [Boolean] 当该字段被设置为 true, 告知在匹配操作中忽略对VARY头信息的匹配。换句话说,当请求 URL 匹配上,你将获取匹配的 Response 对象,无论请求的 VARY 头存在或者没有。该参数默认为 false。
cacheName: [DOMString] 表示所要搜索的缓存名称.

  const req1 = new Request('http://localhost:8008/v3/test-1', {
    method: 'get'
  })
  caches.open('test-cache-name').then(cache => {
    cache.delete(req1).then(res => {
      console.log(res); // true
    })
  })

6. cache.keys(request,{options})

  const req3 = new Request('http://localhost:8008/v3/test-3', {
    method: 'get'
  })
  caches.open('test-cache-name').then(cache => {
    cache.keys().then(res => {
      console.log(res); // [Request, Request, Request]
    })
    cache.keys().then(res => {
      console.log(res); // [Request, Request, Request]
    })
    cache.keys(req3).then(res => {
      console.log('req3.....', res); // 返回对应的key req3的[Request]
    })
  })

7. cache.put(request, response)

// url
const url = 'style.css';
fetch(url).then(function(response) {
  if (!response.ok) {
    throw new TypeError('Bad response status');
  }
  return cache.put(url, response);
})
// Request
const req1 = new Request('http://localhost:8008/v3/test-1', {
  method: 'get'
})
fetch(req1).then(res => {
  cache.put(req1, res)
})
上一篇 下一篇

猜你喜欢

热点阅读