[PWA] sw-precache

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PWA] sw-precache相关的知识,希望对你有一定的参考价值。

Link to CodeLab

 

 In this codelab, we‘ll retrace those steps but this time we‘ll use a tool called sw-precache to add offline functionality with only six lines of code. It‘s never been easier to add service worker support to an existing app, and we‘ll show you how in this codelab.

 

Learning:

  • What the sw-precache tool is and how it can help you be more productive
  • How to add a basic service worker to an existing project using sw-precache

 

Install:

git clone https://github.com/GoogleChrome/airhorn.git
cd airhorn
git checkout code-lab
npm install
npm install --save-dev sw-precache cd app python
-m SimpleHTTPServer 3000

 

Gulp:

// Generate sw.js
gulp.task(generate-service-worker, function(callback) {
  var path = require(path);
  var swPrecache = require(sw-precache);
  var rootDir = app;

  swPrecache.write(path.join(rootDir, sw.js), {
    staticFileGlobs: [rootDir + /**/*.{js,html,css,png,jpg,gif,mp3}],
    stripPrefix: rootDir
  }, callback);
});

 

Run:

gulp generate-service-worker

Then in app folder, you should see sw.js file generated.

 

HTML: inisde index.html:

            <script>
                  if (serviceWorker in navigator) {
                        navigator.serviceWorker.register(/sw.js).then(function() {
                              console.log("Service Worker Registered");
                        });
                  }
            </script>

 

Verify Your App:

cd app
python -m SimpleHTTPServer 3000

Open chrome://serviceworker-internals/ in Chrome. This will show you a list of all the registered service workers, which you can use to verify your service worker has indeed properly registered.

 

Kill the serve and reload the page, everything should work as the same.

 

以上是关于[PWA] sw-precache的主要内容,如果未能解决你的问题,请参考以下文章

[io PWA] Great libraries and tools for great Progressive Web Apps

iis不支持pwa

PWA 与 Android 应用程序/服务的互操作性?

如何在移动设备上发送推送通知(Android Chrome)PWA

如何控制 PWA 是使用缓存版本还是获取最新版本?

如何在使用 reactjs 构建的 PWA 应用中切换摄像头?