Workbox----常用建议

此页面包含可以与Workbox一起使用的一组示例缓存策略。

谷歌字体

谷歌字体服务包含两部分

  • 具有@font-face的定义的样式表,会链接字体文件
  • 静态的修订版的字体文件

样式表可以经常更改,因此最好在重新验证时使用陈旧之类的缓存策略来检查每个请求的更新。另一方面,字体文件本身不会更改,可以利用缓存优先策略。
在这里,我们将缓存字体文件的有效期限制为一年(与HTTP Cache-Control标头匹配),最大限制个数为30(以确保我们不会用完用户设备上的过多存储空间)。

import {registerRoute} from 'workbox-routing';
import {CacheFirst, StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';

// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
registerRoute(
  ({url}) => url.origin === 'https://fonts.googleapis.com',
  new StaleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  })
);

// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
  ({url}) => url.origin === 'https://fonts.gstatic.com',
  new CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24 * 365,
        maxEntries: 30,
      }),
    ],
  })
);

缓存图片

通过与请求的预期目标进行匹配,您可能希望对图像使用缓存优先策略。

import {registerRoute} from 'workbox-routing';
import {ExpirationPlugin} from 'workbox-expiration';

registerRoute(
  ({request}) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  })
);

缓存css和js文件

您可能希望通过与传入请求进行匹配,对未预缓存的CSS和JavaScript文件使用“过时验证”策略。

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

registerRoute(
  ({request}) => request.destination === 'script' ||
                  request.destination === 'style',
  new StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);

缓存多个源的内容

通过将多个检查组合到单个matchCallback函数中,可以创建正则表达式以在一条路由中缓存来自多个源的相似请求。

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

registerRoute(
  ({url}) => url.origin === 'https://fonts.googleapis.com' ||
             url.origin === 'https://fonts.gstatic.com',
  new StaleWhileRevalidate(),
);

限制特定源的缓存

您可以缓存特定来源的静态资源,并在该缓存上应用到期规则。例如,下面的示例最多缓存50个请求,缓存有效期5分钟。

import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';

registerRoute(
  ({url}) => url.origin === 'https://hacker-news.firebaseio.com',
  new CacheFirst({
      cacheName: 'stories',
      plugins: [
        new ExpirationPlugin({
          maxEntries: 50,
          maxAgeSeconds: 5 * 60, // 5 minutes
        }),
        new CacheableResponsePlugin({
          statuses: [0, 200],
        }),
      ],
  })
);

对于网络请求强制一个超时时间

可能存在一些网络请求,如果直接是通过网络提供服务,则可能会比较好,但如果网络请求的时间过长,则可以通过缓存提供服务会比较好。

为此,可以使用配置了networkTimeoutSeconds选项的NetworkFirst策略。

import {registerRoute} from 'workbox-routing';
import {NetworkFirst} from 'workbox-strategies';
import {ExpirationPlugin} from 'workbox-expiration';

registerRoute(
  ({url}) => url.origin === 'https://hacker-news.firebaseio.com',
  new NetworkFirst({
    networkTimeoutSeconds: 3,
    cacheName: 'stories',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 5 * 60, // 5 minutes
      }),
    ],
  })
);

从一个特定的子目录缓存资源

您可以通过检查传递给matchCallback函数的URL对象的origin和pathname属性,将请求路由到本地Web应用程序中特定目录中的文件:

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

registerRoute(
  ({url}) => url.origin === self.location.origin &&
             url.pathname.startsWith('/static/'),
  new StaleWhileRevalidate()
);

根据资源类型缓存资源

您可以使用请求目标的枚举类型来确定策略。例如,当目标是数据时:

import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {ExpirationPlugin} from 'workbox-expiration';

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

在你的web app的代码中访问缓存

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

// Call addToCache whenever you'd like. E.g. to add to cache after a page load:
window.addEventListener('load', () => {
  // ...determine the list of related URLs for the current page...
  addToCache(['/static/relatedUrl1', '/static/relatedUrl2']);
});

然后,在service worker中设置路由时可以引用缓存名称“ my-cache”,并且该路由可以使用网页本身已经添加的任何缓存条目:

// Inside service-worker.js:

import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

registerRoute(
  ({url}) => url.origin === self.location.origin &&
             url.pathname.startsWith('/static/'),
  new StaleWhileRevalidate({
    cacheName: 'my-cache', // Use the same cache name as before.
  })
);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
vite-plugin-pwa是一个vite的官方插件,它可以通过简单的配置将你的vite项目转变成一个PWA(Progressive Web App)应用。它使用谷歌开源库workbox来实现service worker的功能,并为缓存做了大量的逻辑代码处理,同时还支持多种不同的缓存策略。此外,vite-plugin-pwa还提供了更新sw.js文件的策略,并且它的配置非常简单。使用vite-plugin-pwa可以使你的应用具备离线访问、消息推送等PWA的特性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vite-plugin-pwa:Vite的零配置PWA](https://download.csdn.net/download/weixin_42115074/15088884)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vite-plugin-pwa配置详解](https://blog.csdn.net/YMX2020/article/details/130882745)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [vite pwa项目使用](https://blog.csdn.net/qq_40055200/article/details/130857483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值