2017-02-07 30 views
1

我的网站有6个不同的内容元素,我想通过服务人员特定的缓存方法进行控制。ServiceWorker ifs为特定内容定义特定缓存

  1. [预缓存]静态内容(CSS,JS,字体)
  2. [缓存回退到互联] CDN(从CloudFront的S3图像)
  3. [网络后备缓存] INDEX (主页)
  4. [缓存回退到互联] PAGES(domain.com/sth - > HTML)
  5. [通] API(AJAX调用)
  6. [通]其他的东西(分析,标签管理器)

我制成内部ServiceWorker 6个IFS取事件。

我的问题是...这是一个好方法吗?不是方法...因为它是特定于我的网站/博客。但是,你如何看待这些ifs?过滤特定内容并使用适当的缓存是否正确?

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) 
}) 

回答

0

你为什么要划分内容。

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

只需在制作API调用时检查content-type并且不要缓存这些响应。

只是将内容分成两类。Cache-able/Non Cache-able

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