* Not available yet
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', {
scope: '/api/'
}).then(function (sw) {
// registration worked
}).catch(function () {
// registration failed
});
}
register() is idempotent - it can be called multiple times without spawning multiple identical workers.
var urlsToCache = [
'/',
'/assets/bundle.css',
'/assets/bundle.js'
];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open('the-cool-app-1.0.0')
.then(function (cache) {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function(event) {
var usedCaches = ['static-1.3.0', 'api-1.0.0'];
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (usedCaches.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
Both Request and Response objects are streams and can only be consumed once.
Use clone() to consume them more than once!
self.addEventListener('fetch', function(event) {
var response = caches.match(event.request).then(function(cached) {
// Check cache hit
if (cached) {
return cached;
}
// Clone request, will be consumed by cache.put(...).
return fetch(event.request.clone()).then(function (fetched) {
// (Check for HTTP status code omitted for brevity)
caches.open('my-cache-1.0.0').then(function (cache) {
// Clone fetched response, will be consumed by browser.
cache.put(event.request, fetched.clone());
});
return fetched;
});
});
event.respondWith(response);
});