1
0

sw.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. "use strict";
  2. //console.log('WORKER: executing.');
  3. /* A version number is useful when updating the worker logic,
  4. allowing you to remove outdated cache entries during the update.
  5. */
  6. var version = 'v1.0.0::';
  7. /* These resources will be downloaded and cached by the service worker
  8. during the installation process. If any resource fails to be downloaded,
  9. then the service worker won't be installed either.
  10. */
  11. var offlineFundamentals = [
  12. // add here the files you want to cache
  13. 'favicon.ico'
  14. ];
  15. /* The install event fires when the service worker is first installed.
  16. You can use this event to prepare the service worker to be able to serve
  17. files while visitors are offline.
  18. */
  19. self.addEventListener("install", function (event) {
  20. //console.log('WORKER: install event in progress.');
  21. /* Using event.waitUntil(p) blocks the installation process on the provided
  22. promise. If the promise is rejected, the service worker won't be installed.
  23. */
  24. event.waitUntil(
  25. /* The caches built-in is a promise-based API that helps you cache responses,
  26. as well as finding and deleting them.
  27. */
  28. caches
  29. /* You can open a cache by name, and this method returns a promise. We use
  30. a versioned cache name here so that we can remove old cache entries in
  31. one fell swoop later, when phasing out an older service worker.
  32. */
  33. .open(version + 'fundamentals')
  34. .then(function (cache) {
  35. /* After the cache is opened, we can fill it with the offline fundamentals.
  36. The method below will add all resources in `offlineFundamentals` to the
  37. cache, after making requests for them.
  38. */
  39. return cache.addAll(offlineFundamentals);
  40. })
  41. .then(function () {
  42. //console.log('WORKER: install completed');
  43. })
  44. );
  45. });
  46. /* The fetch event fires whenever a page controlled by this service worker requests
  47. a resource. This isn't limited to `fetch` or even XMLHttpRequest. Instead, it
  48. comprehends even the request for the HTML page on first load, as well as JS and
  49. CSS resources, fonts, any images, etc.
  50. */
  51. self.addEventListener("fetch", function (event) {
  52. //console.log('WORKER: fetch event in progress.');
  53. /* We should only cache GET requests, and deal with the rest of method in the
  54. client-side, by handling failed POST,PUT,PATCH,etc. requests.
  55. */
  56. if (event.request.method !== 'GET') {
  57. /* If we don't block the event as shown below, then the request will go to
  58. the network as usual.
  59. */
  60. //console.log('WORKER: fetch event ignored.', event.request.method, event.request.url);
  61. return;
  62. }
  63. /* Similar to event.waitUntil in that it blocks the fetch event on a promise.
  64. Fulfillment result will be used as the response, and rejection will end in a
  65. HTTP response indicating failure.
  66. */
  67. event.respondWith(
  68. caches
  69. /* This method returns a promise that resolves to a cache entry matching
  70. the request. Once the promise is settled, we can then provide a response
  71. to the fetch request.
  72. */
  73. .match(event.request)
  74. .then(function (cached) {
  75. /* Even if the response is in our cache, we go to the network as well.
  76. This pattern is known for producing "eventually fresh" responses,
  77. where we return cached responses immediately, and meanwhile pull
  78. a network response and store that in the cache.
  79. Read more:
  80. https://ponyfoo.com/articles/progressive-networking-serviceworker
  81. */
  82. var networked = fetch(event.request)
  83. // We handle the network request with success and failure scenarios.
  84. .then(fetchedFromNetwork, unableToResolve)
  85. // We should catch errors on the fetchedFromNetwork handler as well.
  86. .catch(unableToResolve);
  87. /* We return the cached response immediately if there is one, and fall
  88. back to waiting on the network as usual.
  89. */
  90. //console.log('WORKER: fetch event', cached ? '(cached)' : '(network)', event.request.url);
  91. return cached || networked;
  92. function fetchedFromNetwork(response) {
  93. /* We copy the response before replying to the network request.
  94. This is the response that will be stored on the ServiceWorker cache.
  95. */
  96. var cacheCopy = response.clone();
  97. //console.log('WORKER: fetch response from network.', event.request.url);
  98. caches
  99. // We open a cache to store the response for this request.
  100. .open(version + 'pages')
  101. .then(function add(cache) {
  102. /* We store the response for this request. It'll later become
  103. available to caches.match(event.request) calls, when looking
  104. for cached responses.
  105. */
  106. cache.put(event.request, cacheCopy);
  107. })
  108. .then(function () {
  109. //console.log('WORKER: fetch response stored in cache.', event.request.url);
  110. });
  111. // Return the response so that the promise is settled in fulfillment.
  112. return response;
  113. }
  114. /* When this method is called, it means we were unable to produce a response
  115. from either the cache or the network. This is our opportunity to produce
  116. a meaningful response even when all else fails. It's the last chance, so
  117. you probably want to display a "Service Unavailable" view or a generic
  118. error response.
  119. */
  120. function unableToResolve() {
  121. /* There's a couple of things we can do here.
  122. - Test the Accept header and then return one of the `offlineFundamentals`
  123. e.g: `return caches.match('/some/cached/image.png')`
  124. - You should also consider the origin. It's easier to decide what
  125. "unavailable" means for requests against your origins than for requests
  126. against a third party, such as an ad provider.
  127. - Generate a Response programmatically, as shown below, and return that.
  128. */
  129. //console.log('WORKER: fetch request failed in both cache and network.');
  130. /* Here we're creating a response programmatically. The first parameter is the
  131. response body, and the second one defines the options for the response.
  132. */
  133. return new Response('<h1>Service Unavailable</h1>', {
  134. status: 503,
  135. statusText: 'Service Unavailable',
  136. headers: new Headers({
  137. 'Content-Type': 'text/html'
  138. })
  139. });
  140. }
  141. })
  142. );
  143. });
  144. /* The activate event fires after a service worker has been successfully installed.
  145. It is most useful when phasing out an older version of a service worker, as at
  146. this point you know that the new worker was installed correctly. In this example,
  147. we delete old caches that don't match the version in the worker we just finished
  148. installing.
  149. */
  150. self.addEventListener("activate", function (event) {
  151. /* Just like with the install event, event.waitUntil blocks activate on a promise.
  152. Activation will fail unless the promise is fulfilled.
  153. */
  154. //console.log('WORKER: activate event in progress.');
  155. event.waitUntil(
  156. caches
  157. /* This method returns a promise which will resolve to an array of available
  158. cache keys.
  159. */
  160. .keys()
  161. .then(function (keys) {
  162. // We return a promise that settles when all outdated caches are deleted.
  163. return Promise.all(
  164. keys
  165. .filter(function (key) {
  166. // Filter by keys that don't start with the latest version prefix.
  167. return !key.startsWith(version);
  168. })
  169. .map(function (key) {
  170. /* Return a promise that's fulfilled
  171. when each outdated cache is deleted.
  172. */
  173. return caches.delete(key);
  174. })
  175. );
  176. })
  177. .then(function () {
  178. //console.log('WORKER: activate completed.');
  179. })
  180. );
  181. });