首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ServiceWorker ifs为特定内容定义特定的缓存

ServiceWorker ifs为特定内容定义特定的缓存
EN

Stack Overflow用户
提问于 2017-02-07 21:31:52
回答 1查看 68关注 0票数 1

我的网站有6个不同的内容元素,我想通过服务工作者特定的缓存方法来控制。

  1. 预缓存静态内容(css、js、字体)
  2. 缓存回网络 CDN (来自CloudFront S3的图像)
  3. 网络回退到缓存索引(主页)
  4. 缓存回网络页面(domain.com/ -> html)
  5. 传递 API (ajax调用)
  6. 传递其他东西(分析,标签管理器)

我在ServiceWorker fetch事件中做了6个ifs。

我的问题是..。这是个好方法吗?不是方法..。因为它是特定于我的网站/博客。但如果那样的话你会怎么想?它是过滤特定内容并使用适当缓存的正确方法吗?

代码语言:javascript
复制
var domain = location.host.split('.')[0]

regexStatic = new RegExp('https://' + location.host + '/build/(.*)')
regexCdn = new RegExp('https://cdn.' + domain + '(.*)')
regexIndex = new RegExp('https://' + location.host + '/')
regexApi = new RegExp('https://' + location.host + '/api/(.*)')
regexPages = new RegExp('https://' + location.host + '/(.*)')

self.addEventListener('fetch', function (event) {
  // STATIC
  if (regexStatic.test(event.request.url)) {
    event.respondWith(
      //
    )
    return
  }

  // CDN
  if (regexCdn.test(event.request.url)) {
    event.respondWith(
      //
    )
    return
  }

  // INDEX
  if (regexIndex.test(event.request.url)) {
    event.respondWith(
      //
    )
    return
  }

  // API
  if (regexApi.test(event.request.url)) {
    return
  }

  // PAGES
  if (regexPages.test(event.request.url)) {
    event.respondWith(
      //
    )
    return
  }

  // OTHER
  console.log('NOT INCLUDED IN CACHE: ', event.request.url)
})
EN

回答 1

Stack Overflow用户

发布于 2017-02-08 07:13:22

你为什么要分割内容。

如果在缓存中找不到内容,则会自动转发到网络进行获取,否则将提供本地缓存副本。

只需在进行API调用时检查content-type,不要缓存这些响应。

只需将内容分为两类。Cache-able/ Non Cache-able.

在这里获得更多信息:https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42100378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档