2019-07-10 19:48:36 +02:00
<%# The name of the cache to store responses in %>
<%# If the cache name changes DevDocs is assumed to be updated %>
const cacheName = '<%= service_worker_cache_name %>';
2019-07-07 00:55:58 +02:00
2019-07-08 01:42:34 +02:00
<%# Url's to cache when the service worker is installed %>
const urlsToCache = [
2019-07-07 00:55:58 +02:00
'/',
'/favicon.ico',
'/manifest.json',
2019-07-07 14:30:31 +02:00
'<%= service_worker_asset_urls.join "',\n '" %>',
'<%= doc_index_urls.join "',\n '" %>',
2019-07-07 00:55:58 +02:00
];
<%# Set-up the cache %>
self.addEventListener('install', event => {
self.skipWaiting();
event.waitUntil(
2019-07-08 01:42:34 +02:00
caches.open(cacheName).then(cache => cache.addAll(urlsToCache)),
2019-07-07 00:55:58 +02:00
);
});
<%# Remove old caches %>
self.addEventListener('activate', event => {
2019-07-07 03:25:42 +02:00
event.waitUntil((async () => {
const keys = await caches.keys();
const jobs = keys.map(key => key !== cacheName ? caches.delete(key) : Promise.resolve());
2019-07-07 14:11:39 +02:00
return Promise.all(jobs);
2019-07-07 03:25:42 +02:00
})());
2019-07-07 00:55:58 +02:00
});
<%# Handle HTTP requests %>
self.addEventListener('fetch', event => {
2019-07-07 03:25:42 +02:00
event.respondWith((async () => {
const cachedResponse = await caches.match(event.request);
if (cachedResponse) return cachedResponse;
2019-07-12 03:06:04 +02:00
const url = new URL(event.request.url);
<%# Attempt to return the index page from the cache if the user is visiting a url like devdocs.io/offline or devdocs.io/javascript/global_objects/array/find %>
<%# The index page will handle the routing %>
if (url.origin === location.origin && !url.pathname.includes('.')) {
const cachedIndex = await caches.match('/');
if (cachedIndex) return cachedIndex;
2019-07-07 03:25:42 +02:00
}
2019-07-12 03:06:04 +02:00
return fetch(event.request);
2019-07-07 03:25:42 +02:00
})());
2019-07-07 00:55:58 +02:00
});