Workbox 介绍

4.24

介绍

Workbox 是一系列库和 Node 模块。用于缓存资源和构建 Progressive Web Apps(PWA)。

PWA 应用的用户体验能达到较高的水平

  • Reliable 不管网络环境如何都能立即加载

  • Fast 用户交互时能立即响应

  • Engaging 像原生应用一样的体验

Why Workbox

  • 预缓存 Precaching
  • 运行时缓存 Runtime caching
  • 策略 Strategies
  • 请求路由 Request routing
  • 后台同步 Background sync
  • 方便调试 Helpful debugging

使用

Workbox 可以和 service worker 一起使用。Get Started

注册 service worker

service-worker.js

console.log('Hello from service-worker.js');

index.html

<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js');
  });
}
</script>

可以在 Chrome 开发工具的 Application > Service Workers 查看。建议选中Update on Reload 便于后续的开发。

加载 Workbox

直接使用

service-worker.js

importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');

// or download to local
importScripts('./4.3.1/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}

使用打包工具

比如使用 npm 安装, webpack 打包生成 service-worker.js

import {precaching} from 'workbox-precaching'
import {registerRoute} from 'workbox-routing'
import {BackgroundSyncPlugin} from 'workbox-background-sync'

// Use the above modules somehow

路由处理, 缓存 JavaScript 请求

可以对指定的路由添加缓存策略。

service-worker.js

workbox.routing.registerRoute(
  /\.js$/,
  new workbox.strategies.NetworkFirst()
);

路由处理,缓存 CSS、Images 等请求

service-worker.js

workbox.routing.registerRoute(
  // Cache CSS files.
  /\.css$/,
  // Use cache but update in the background.
  new workbox.strategies.StaleWhileRevalidate({
    // Use a custom cache name.
    cacheName: 'css-cache',
  })
);

workbox.routing.registerRoute(
  // Cache image files.
  /\.(?:png|jpg|jpeg|svg|gif)$/,
  // Use the cache if it's available.
  new workbox.strategies.CacheFirst({
    // Use a custom cache name.
    cacheName: 'image-cache',
    plugins: [
      new workbox.expiration.Plugin({
        // Cache only 20 images.
        maxEntries: 20,
        // Cache for a maximum of a week.
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
);

缓存机制应用于同域名下的文件,可在 Appliction > Cache Storage 中查看。

预缓存文件 / Precache Files

在安装 serviceWorker 之前提前下载和缓存相关文件,便于离线使用和加速。

workbox.precaching.precacheAndRoute([
    '/styles/index.0c9a31.css',
    '/scripts/main.0d5770.js',
    { url: '/index.html', revision: '383676' },
]);

Webpack 构建环境可以参考:Precache Files with Webpack

📖