service-worker.js.erb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <%# The name of the cache to store responses in %>
  2. <%# If the cache name changes DevDocs is assumed to be updated %>
  3. const cacheName = '<%= service_worker_cache_name %>';
  4. <%# Url's to cache when the service worker is installed %>
  5. const urlsToCache = [
  6. '/',
  7. '/favicon.ico',
  8. '/manifest.json',
  9. '<%= service_worker_asset_urls.join "',\n '" %>',
  10. '<%= doc_index_urls.join "',\n '" %>',
  11. ];
  12. <%# Set-up the cache %>
  13. self.addEventListener('install', event => {
  14. self.skipWaiting();
  15. event.waitUntil(
  16. caches.open(cacheName).then(cache => cache.addAll(urlsToCache)),
  17. );
  18. });
  19. <%# Remove old caches %>
  20. self.addEventListener('activate', event => {
  21. event.waitUntil((async () => {
  22. const keys = await caches.keys();
  23. const jobs = keys.map(key => key !== cacheName ? caches.delete(key) : Promise.resolve());
  24. return Promise.all(jobs);
  25. })());
  26. });
  27. <%# Handle HTTP requests %>
  28. self.addEventListener('fetch', event => {
  29. event.respondWith((async () => {
  30. const cachedResponse = await caches.match(event.request);
  31. if (cachedResponse) return cachedResponse;
  32. const url = new URL(event.request.url);
  33. <%# 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 %>
  34. <%# The index page will handle the routing %>
  35. if (url.origin === location.origin && !url.pathname.includes('.')) {
  36. const cachedIndex = await caches.match('/');
  37. if (cachedIndex) return cachedIndex;
  38. }
  39. return fetch(event.request);
  40. })());
  41. });