最简单示例程序
在index.html中添加
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
</script>
和index.html同位置放置sw.js
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'/',
'/index.html',
'/jquery.min.js',
'/files/pa.png',
'/files/pc.png',
'/files/pc1.png',
'/files/pc2.png',
'/files/pc3.png'
];
var num = 0;
var PRO = null;
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
//return cache.addAll(urlsToCache);
getnext(cache);
return PRO;
})
);
});
function getnext(cache){
var pro = cache.add(urlsToCache[num]);
num++;
if(num < urlsToCache.length){
pro.then(() => {
console.log("download: "+num+" "+Date.now());
getnext(cache);
});
}
else{
PRO = pro;
}
}
this.addEventListener('fetch', function (event) {
//console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(res => {
return res ||
fetch(event.request)
.then(responese => {
console.log(event.request.url+"need download!");
const responeseClone = responese.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, responeseClone);
})
return responese;
})
.catch(err => {
console.log(err);
});
})
)
});
在install中,我用cache.add代替了cache.addall,这样是为了能有一个基本的加载进度显示。