I’m building a Service Worker component. I want it to have:
See it for yourself
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/worker.js').then(function(reg) {
navigator.serviceWorker.controller.postMessage({
'hello': 'world',
cacheName: 'v1',
urlsToCache: [
"/index.html"
]
});
}, function(err) {
console.log('ಠ_ಠ Nope.', err);
});
}
'use strict';
var cacheName,
urlsToCache;
importScripts('/node_modules/serviceworker-cache-polyfill/index.js');
self.addEventListener('message', function (evt) {
cacheName = evt.data.cacheName;
urlsToCache = evt.data.urlsToCache;
});
self.addEventListener('install', function(event) {
setTimeout(function(){
event.waitUntil(
caches.open(cacheName)
.then(function(cache) {
console.log('Opened cache:', cache);
return cache.addAll(urlsToCache);
})
);
}, 2000);
});
I had to delay the opening of the cache by using a setTimeout, which is wrong, ugly and unreliable.
I want to find a way to tell the worker to wait until the message containing the paths to cache arrives.
Link to my repo
Thanks in advance.
I've sent you a Pull Request: https://github.com/cristianelias/serviceworker_component/pull/1. Basically what I did is use the cache object from the page itself as follow:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/worker.js').then(function(reg) {
caches.open('pages').then(function(pages){
return pages.add('test.html');
}).then(function(){
console.log('cached!');
});
}, function(err) {
console.log('ಠ_ಠ Nope.', err);
});
}
And instructed the SW to only perform a cache match:
'use strict';
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(match){
return match || fetch(event.request);
})
);
});
It works as expected on Chrome 45, I don't know on older versions since moving the cache object to the page is quite a new thing.