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

 

posted @   Zhentiw  阅读(348)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示