JavaScriptService worker / Workbox

Getting started Workbox

I've try to use Workbox by Getting started documents. Make base html files At first, we need to make base […]

広告ここから
広告ここまで

I've try to use Workbox by Getting started documents.

Make base html files

At first, we need to make base simple webpage.

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello workbox</title>
  </head>
  <body>
    <div id="root">
      <h1>Hello workbox</h1>
    </div>
    <script src="./scripts/app.js"></script>
  </body>
</html>

scripts/app.js

console.log('Welcome to my app')

Loading Workbox by Service Worker scripts

Add sw.js file and add code to load Workbox. 

sw.js

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
if (workbox) {
  console.log('Yeah! workbox did load')
} else {
  console.log('Oh, workbox did not load')
}

Update index.html

Update index.html to call sw.js and register Service Worker.

<script src="./scripts/app.js"></script>
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('./sw.js')
    })
  }
</script>

Preparation is complete ! Let's start to use WorkBox.

Cache JS files

First, add workbox.routing.registeRoute() to cache JavaScript files.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
if (workbox) {
  workbox.routing.registerRoute(
    new RegExp('.*.js'),
    workbox.strategies.networkFirst()
  )
} else {
  console.log('Oh, workbox did not load')
}

We can use regular expression to match file name.

We can check caching status on Developer tool's Application tab.

Caching CSS and IMAGE files

Of course we can cache CSS and image files.

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
if (workbox) {
  registerRoutes()
} else {
  console.log('Oh, workbox did not load')
}

function registerRoutes() {
  workbox.routing.registerRoute(
    new RegExp('.*.js'),
    workbox.strategies.networkFirst()
  )
  workbox.routing.registerRoute(
    /.*.css/,
    workbox.strategies.staleWhileRevalidate({
      cacheName: 'css-cache',
    })
  )
  workbox.routing.registerRoute(
    /.*.(?:png|jpg|jpeg|svg|gif)/,
    workbox.strategies.cacheFirst({
      cacheName: 'image-cache',
      plugins: [
        new workbox.expiration.Plugin({
          maxEntries: 20,
          maxAgeSeconds: 7 * 24 * 60 * 60,
        })
      ]
    })
  )
}

Finally, we can check the caching status.

Example source code

GitHub: https://github.com/hideokamoto/workbox-practice/tree/20180320

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts