PWA - service worker - Workbox(未完)

Get Started(開始)

  • 只有get請求才能cache緩存嗎?

Create and Register a Service Worker File(建立和註冊 Service Worker)

  • Before we can use Workbox, we need to create a service worker file and register it to our website.(在使用Workbox以前,咱們須要建立一個服務工做者文件並將其註冊到咱們的網站。)
<script>
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>
  • Looking in the 「Application」 tab in Chrome DevTools you should see your service worker registered.(在chrome devtools中的「application」選項卡中,您應該看到服務工做者已註冊。)
    • Click the 「Update on reload」 checkbox to make it easier to develop with your new service worker.(單擊 「Update on reload」 複選框,以便與新的 service worker 一塊兒開發。)

Importing Workbox(導入工做框)

  • To start using Workbox you just need to import the workbox-sw.js file in your service worker.(要開始使用Workbox,只需在服務工做者中導入Workbox-sw.js文件。)
    • Importing workbox-sw.js will create a workbox object inside of your service worker, and that instance is responsible for importing other helper libraries, based on the features you use.(導入workbox-sw.js將在服務工做者內部建立一個workbox對象,該實例負責根據您使用的功能導入其餘助手庫。)
    • Due to restrictions in the service worker specification, these imports need to happen either inside of an install event handler, or synchronously in the top-level code for your service worker.(因爲 service worker 規範中的限制,這些導入須要在安裝事件處理程序內部或在服務工做者的頂級代碼中同步進行。?)
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); // 同步的

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

Using Workbox

  • The easiest way to do this is to register a route with Workbox that will match any .js files that are requested, which we can do with a regular expression:(在Workbox中註冊一個路由,這裏咱們使用正則表達式去匹配請求的任何.js文件)
  • If we want our JavaScript files to come from the network whenever possible, but fallback to the cached version if the network fails, we can use the 「network first」 strategy to achieve this.(若是咱們但願咱們的javascript文件儘量來自網絡,可是若是網絡失敗,咱們能夠回退到緩存版本,咱們可使用「network first」策略來實現這一點。)
workbox.routing.registerRoute(
  new RegExp('.*\.js'),
  new workbox.strategies.NetworkFirst()
);
  • Add this code to your service worker and refresh the page. If your web page has JavaScript files in it, you should see some logs similar to this:(在控制檯會有相應策略的打印提醒)

  • Workbox provides a few caching strategies that you can use.(Workbox提供了一些您可使用的緩存策略。)
  • your CSS could be served from the cache first and updated in the background(能夠先從緩存中提供CSS,而後在後臺進行更新。)
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',
  })
);
  • your images could be cached and used until it’s a week old, after which it’ll need updating.(使圖像被緩存並使用一週,一週後才更新。)
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.(只有20個圖像)
        maxEntries: 20,
        // Cache for a maximum of a week.(最多一週的緩存。)
        maxAgeSeconds: 7 * 24 * 60 * 60,
      })
    ],
  })
);

What Else Can Workbox Do?

  • Routing and caching strategies are performed by the routing and strategies modules, but there are plenty of other modules, each offering specific behaviors that you can use in your service worker.(路由和緩存策略是由路由和策略模塊執行的,可是還有許多其餘模塊,每一個模塊都提供能夠在服務工做者中使用的特定行爲。)

Precache Files(預緩存文件)

  • If you want your web app to work offline or there are assets you know can be cached for a long time, precaching is the best approach.(當須要離線使用網頁或有須要加載好久的資源時,使用預緩存)
  • Workbox provides an easy way to precache files, ensuring that as your service worker changes, the precached files are maintained efficiently, only downloading updated files and cleaning up after the service worker is made redundant.(Workbox提供了一種簡單的預緩存文件的方法,確保隨着服務工做者的更改,預緩存文件獲得有效的維護,只下載更新的文件,並在服務工做者被冗餘後進行清理。)
  • The above snippet will download the files /styles/index.0c9a31.css, /scripts/main.0d5770.js and /index.html during the service worker install event and create a route that serves these files directly from the cache.(上述代碼段將在ServiceWorker安裝事件期間下載文件/styles/index.0c9a31.css、/scripts/main.0d5770.js和/index.html,並建立直接從緩存爲這些文件提供服務的路由。)
  • This list of files is normally generated using a tool that manages the versioning of files.(此文件列表一般使用管理文件版本控制的工具生成。)
workbox.precaching.precacheAndRoute([
    '/styles/index.0c9a31.css',
    '/scripts/main.0d5770.js',
    { url: '/index.html', revision: '383676' },
]);

Generating a Precache Manifest(生成預緩存清單)

  • Below is a list of tools that can generate this list of files.(下面是能夠生成此文件列表的工具列表。)
    • Workbox Command Line Interface (CLI):Ideal for developers who are unfamiliar with Node or have simple needs.(很是適合不熟悉節點或有簡單需求的開發人員。)
    • workbox Build:Perfect for developers wanting to programmatically build the list in Node or are using Gulp for their build process.(很是適合但願以編程方式在節點中構建列表或在其構建過程當中使用Gulp的開發人員。)
    • Workbox Webpack Plugin:Ideal for developers using webpack to build their project.(很是適合使用Webpack構建項目的開發人員。)

CLI(Precache Files with Workbox CLI)

Gulp or Node(Precache Files with workbox-build)

Webpack(Precache Files with Webpack)

  • 稍後

Route Requests(路由請求)

  • There are three ways developers can match a request with workbox-routing.(開發人員能夠經過三種方式將請求與Workbox路由相匹配。)
    • A string.
    • A regular expression.(正則表達式。)
    • A callback function.(回調函數。)

Matching a Route with a String(將路由與字符串匹配)

  • The only thing to be wary of is that this would only match for requests on your origin. (這隻會與源站上的請求匹配。)
workbox.routing.registerRoute(
  '/logo.png',
  handler // 這裏應該是處理程序,這個例子先用handler佔個位置,如下同
);
  • Instead you’d need to define the entire URL to match.(匹配源以外的路徑,須要定義整個URL來匹配。)
workbox.routing.registerRoute(
  'https://some-other-origin.com/logo.png',
  handler
);

Matching a Route with a Regular Expression(將路由與正則表達式匹配)

  • The regular expression provided is tested against the full URL.(提供的正則表達式根據完整的URL進行測試)
workbox.routing.registerRoute(
  new RegExp('\\.js$'),
  jsHandler
);

workbox.routing.registerRoute(
  new RegExp('\\.css$'),
  cssHandler
);

workbox.routing.registerRoute(
  new RegExp('/blog/\\d{4}/\\d{2}/.+'),
  handler
);
  • If we wanted a route that would match that general path pattern made against both same- and cross-origin requests, using a regular expression with a wildcard (.+)at the start is one approach:(若是咱們想要一個路由與針對相同和跨源請求的常規路徑模式相匹配,那麼在開始使用帶有通配符(.+)的正則表達式是一種方法:?不在頭部添加通配符,只能匹配同源的?)
workbox.routing.registerRoute(
  new RegExp('.+/blog/\\d{4}/\\d{2}/.+'),
  handler
);

Matching a Route with a Callback Function(將路由與回調函數匹配)

  • The callback will receive an object with the requests URL and the FetchEvent received in the service worker.(回調將接收一個對象,該對象具備在 service worker 中接收到的請求URL和FetchEvent。)
  • One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(若是在matchFunction回調中返回一個值,它將做爲params參數傳遞處處理程序回調handler中。)
const matchFunction = ({url, event}) => {
  // Return true if the route should match // 路由匹配則返回 true
  return false;
};

workbox.routing.registerRoute(
  matchFunction,
  handler
);

——————————————————————

  • There are two ways you can handle a request:(有兩種方法能夠處理請求:)
    • Use one of Workbox’s strategies provided by workbox.strategies.(使用Workbox.Strategies提供的Workbox策略)
    • Provide a callback function that returns a Promise that resolves to a Response(提供一個回調函數,該函數返回解析爲響應的承諾?)

Handling a Route with a Workbox Strategy(使用 Workbox 策略處理路由)

  • Most routes can be handled with one of the built in caching strategies.(大多數路由均可以經過一種內置的緩存策略來處理。)
    • Stale While Revalidate(緩存優先,隨後更新):This strategy will use a cached response for a request if it is available and update the cache in the background with a response form the network. (If it’s not cached it will wait for the network response and use that). (若是請求可用,則此策略將使用緩存響應,並使用來自網絡的響應在後臺更新緩存。(若是沒有緩存,它將等待網絡響應並使用該響應)。)
    • Network First(網絡優先):This will try and get a request from the network first. If it receives a response, it’ll pass that to the browser and also save it to a cache. If the network request fails, the last cached response will be used.(這將嘗試首先從網絡獲取請求。若是它收到一個響應,它將把它傳遞給瀏覽器,並將其保存到緩存中。若是網絡請求失敗,將使用上次緩存的響應。)
    • Cache First(緩存優先,不更新):This strategy will check the cache for a response first and use that if one is available. If the request isn’t in the cache, the network will be used and any valid response will be added to the cache before being passed to the browser.(此策略將首先檢查緩存。若是請求不在緩存中,則將使用網絡,並在傳遞到瀏覽器以前將任何有效響應添加到緩存中。)
    • Network Only(強制網絡):Force the response to come from the network.(強制響應來自網絡。)
    • Cache Only(強制緩存):Force the response to come from the cache.
workbox.routing.registerRoute(
  match,
  new workbox.strategies.StaleWhileRevalidate()
);

workbox.routing.registerRoute(
  match,
  new workbox.strategies.NetworkFirst()
);

workbox.routing.registerRoute(
  match,
  new workbox.strategies.CacheFirst()
);

workbox.routing.registerRoute(
  match,
  new workbox.strategies.NetworkOnly()
);

workbox.routing.registerRoute(
  match,
  new workbox.strategies.CacheOnly()
);
  • With each strategy you can customize the behavior of the Route by defining a custom cache to use and / or adding plugins.(每一個策略,您能夠定義要使用的緩存名 和 添加插件來定製路由的行爲。定義相同的緩存名會怎樣?有什麼意義?一個緩存名能夠保存一組緩存數據,不一樣的緩存名是爲了保存同一個接口不一樣的返回數據嗎?)
  • These options are often needed to make it safer when caching requests (i.e. limiting how long they are cached or making sure the data used on a device is limited).(緩存請求時,一般須要這些選項以使其更安全。例如:限制緩存的時間或保存空間)
new workbox.strategies.StaleWhileRevalidate({
   // Use a custom cache for this route.(爲此路由使用自定義緩存。)
  cacheName: 'my-cache-name',

  // Add an array of custom plugins (like workbox.expiration.Plugin).(添加一組自定義插件,例如 workbox.expiration.Plugin)
  plugins: [
    ...
  ]
});

Handling a Route with a Custom Callback(使用自定義回調處理路由)

  • you can provide an asyncfunction which returns a Response object.(傳入一個返回 Response 對象的Async Function來處理。)
    • Fetch API 的 Response 接口表明一次請求的響應數據
  • It'll be called with a parameter object containing url and event (the FetchEvent) properties.(它將接收 URL 和 fetchvent 事件對象)
const handler = async ({url, event}) => {
  return new Response(`Custom handler response.`);
};

workbox.routing.registerRoute(match, handler);
  • One thing to note is that if you return a value in the match callback, it’ll be passed into the handler callback as a params argument.(若是在match回調中返回一個值,它將做爲params參數傳遞處處理程序回調中。)
const match = ({url, event}) => {
  return {
    name: 'Workbox',
    type: 'guide',
  };
};

const handler = async ({url, event, params}) => {
   // Response will be "A guide to Workbox"
  return new Response(
    `A ${params.type} to ${params.name}`
  );
};

workbox.routing.registerRoute(match, handler);

Configure Workbox(配置Workbox)

Configure Cache Names(配置緩存名稱)

  • By default, Workbox will only create two caches, one for precaching and one for runtime caching. Using workbox-core you can get the current cache names like so:(默認狀況下,Workbox將只建立兩個緩存,一個用於預緩存,另外一個用於運行時緩存。使用Workbox Core,您能夠得到當前緩存名稱,以下所示:)
const precacheCacheName = workbox.core.cacheNames.precache;
const runtimeCacheName = workbox.core.cacheNames.runtime;
  • Both the precache and runtime cache names are made of three pieces of information:<prefix>-<cacheId>-<suffix>(預緩存和運行時緩存名稱都由三條信息組成:)
  • You can alter the cache names by altering all or some of these pieces of information:(能夠經過更改如下信息來更改緩存名稱:)
  • We recommend changing the prefix for each of your projects. This allows you to work on multiple projects using the same localhost port number without mixing up the caches.(咱們建議更改每一個項目的前綴。這容許您使用相同的本地主機端口號處理多個項目,而不會混淆緩存。)
workbox.core.setCacheNameDetails({
  prefix: 'my-app',
  suffix: 'v1',
  precache: 'custom-precache-name',
  runtime: 'custom-runtime-name'
});

Custom Cache Names in Strategies(策略中自定義緩存名稱)

  • but it’s not uncommon to want additional caches for specific uses, such as a cache just for images.(須要額外的緩存用於特定用途並很多見,例如只用於圖像的緩存。)
  • In these cases, the cache name will be used exactly as you specify; the prefix and suffix will not be used.(在這些狀況下,緩存名稱將徹底按照您指定的方式使用。不會出現前綴和後綴)
/\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'my-image-cache',
  })
);

Custom Fetch Options in Strategies(策略中自定義提取選項)

  • you might find the need to customize some aspects of the outgoing requests.you can pass in a configuration value named fetchOptions to a strategy's constructor, corresponding to the init options used in the underlying Fetch API. (您可能會發現須要自定義傳出請求的某些方面。您能夠將名爲fetchOptions的配置值傳遞給策略的構造函數,對應於底層fetch api中使用的init選項。)
workbox.routing.registerRoute(
  new RegExp('https://third-party\\.example\\.com/'),
  new workbox.strategies.NetworkFirst({
    fetchOptions: {
      credentials: 'include',
    },
  })
);
相關文章
相關標籤/搜索