[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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值