workbox缓存常用范例(译)

此文主要描述Workbox的示例缓存策略

缓存字体(以google服务为例)

Google字体服务由两部分组成:

  • 包含@font-face的样式文件
  • 内部静态的,修订的字体库。

我们知道,样式文件更新比较频繁,优先用“StaleWhileRevalidate”的缓存策略; 而字体库本身不会改变,所以用“cache first”缓存策略。

在这里,我们将缓存的”字体库“的时间限制为一年(匹配HTTP Cache-Control标头),将最大条目限制为30(以确保我们不会在用户的设备上占用过多的存储空间)

 // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.googleapis\.com/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  })
);

// Cache the underlying font files with a cache-first strategy for 1 year.
workbox.routing.registerRoute(
  /^https:\/\/fonts\.gstatic\.com/,
  new workbox.strategies.CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
      new workbox.expiration.Plugin({
        maxAgeSeconds: 60 * 60 * 24 * 365,
        maxEntries: 30,
      }),
    ],
  })
);

缓存图片

你可能希望通过匹配文件“后缀名”,采用“cache-first”策略来缓存图片

 workbox.routing.registerRoute(
  /\.(?:png|gif|jpg|jpeg|webp|svg)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  })
);

缓存css和JS文件

您可能希望对未预先缓存的CSS和JavaScript文件,使用stale-while-revalidate策略。

workbox.routing.registerRoute(
  /\.(?:js|css)$/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);

从多个来源缓存内容

您可以创建正则表达式来缓存来自单个路径中的多个源的类似请求。例如下面,缓存来自googleapis.com和gstatic.com来源的资源

workbox.routing.registerRoute(
  /.*(?:googleapis|gstatic)\.com/,
  new workbox.strategies.StaleWhileRevalidate(),
);

其实就是下面的替代方案

workbox.routing.registerRoute(
  /.*(?:googleapis)\.com/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'googleapis',
  })
);

workbox.routing.registerRoute(
  /.*(?:gstatic)\.com/,
  new workbox.strategies.StaleWhileRevalidate({
    cacheName: 'gstatic',
  })
);

针对来源设置缓存规则

例如,下面的示例缓存最多50个请求,最多5分钟。

workbox.routing.registerRoute(
  'https://hacker-news.firebaseio.com/v0/api',
  new workbox.strategies.CacheFirst({
      cacheName: 'stories',
      plugins: [
        new workbox.expiration.Plugin({
          maxEntries: 50, // 50个
          maxAgeSeconds: 5 * 60, // 5 分钟
        }),
        new workbox.cacheableResponse.Plugin({
          statuses: [0, 200],
        }),
      ],
  })
);

强制网络请求超时

可能存在一些网络请求,他们花费的时间很长,那么通过一些配置,让任何在超时内无法响应的网络请求都强制回退到缓存获取。 为此,您可以使用NetworkFirst策略并配置networkTimeoutSeconds选项。

 workbox.routing.registerRoute(
  'https://hacker-news.firebaseio.com/v0/api',
  new workbox.strategies.NetworkFirst({
      networkTimeoutSeconds: 3,
      cacheName: 'stories',
      plugins: [
        new workbox.expiration.Plugin({
          maxEntries: 50,
          maxAgeSeconds: 5 * 60, // 5 minutes
        }),
      ],
  })
);

从特定子目录缓存资源

您可以使用正则表达式轻松地将请求路由匹配到特定目录中的文件。如果我们想将请求路由匹配到/static/中的文件,我们可以使用正则表达式new RegExp('/ static /'),如下所示:

workbox.routing.registerRoute(
  new RegExp('/static/'),
  new workbox.strategies.StaleWhileRevalidate()
);

基于资源类型的缓存资源

你可以使用RequestDestination确定策略的请求目标类型。比如,当目标是<audio>数据

 workbox.routing.registerRoute(
  // Custom `matchCallback` function
  ({event}) => event.request.destination === 'audio',
  new workbox.strategies.CacheFirst({
    cacheName: 'audio',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  })
);

从Web应用程序代码访问缓存

Cache Storage API可用于service worker和客户端(window)的上下文中。如果要更改缓存 - 添加或删除条目,或从Web应用程序的上下文获取缓存URL列表,您可以直接执行此操作,而无需通过postMessage()与service worker通信。

例如,如果要将URL添加到给定缓存,以响应Web应用程序中的用户操作,则可以使用如下代码:

// Inside app.js:

async function addToCache(urls) {
  const myCache = await window.caches.open('my-cache');
  await myCache.addAll(urls);
}

//随时调用addToCache。例如,在DOM加载后,添加某些路径到缓存:
window.addEventListener('load', () => {
  // ...determine the list of related URLs for the current page...
  addToCache(['/static/relatedUrl1', '/static/relatedUrl2']);
});

在service worker设置缓存规则时,可以引用缓存名称

// Inside service-worker.js:

workbox.routing.registerRoute(
  new RegExp('/static/'),
  new workbox.strategies.StaleWhileRevalidate({
  //'my-cache是之前已经配置缓存名称,这里可以直接指定使用
  cacheName: 'my-cache',  
      })
);

以上为workbox 官网common-recipes章节的搬运,如理解有误,请指正,感谢;

原文: common-recipes

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 参考《深入理解浏览器的缓存机制》进行整理 前言 缓存可以说是性能优化中简单高效的一种优化方式了。一个优秀的缓存策略...
    琢磨先生lf阅读 754评论 1 1
  • 一、前言 缓存可以说是性能优化中简单高效的一种优化方式了。一个优秀的缓存策略可以缩短网页请求资源的距离,减少延迟,...
    沉落的星星阅读 396评论 0 0
  • 一、前言 缓存可以说是性能优化中简单高效的一种优化方式了。一个优秀的缓存策略可以缩短网页请求资源的距离,减少延迟,...
    浪里行舟阅读 207,093评论 46 521
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,451评论 0 9
  • {"box-model": false,"adjoining-classes": false,"box-sizin...
    愿你如夏日清凉的风阅读 668评论 0 0