Guest User

Untitled

a guest
Feb 19th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. self.addEventListener('fetch', function(event) {
  2. event.respondWith(
  3. // This method looks at the request and
  4. // finds any cached results from any of the
  5. // caches that the Service Worker has created.
  6. caches.match(event.request)
  7. .then(function(response) {
  8. // If a cache is hit, we can return thre response.
  9. if (response) {
  10. return response;
  11. }
  12.  
  13. // Clone the request. A request is a stream and
  14. // can only be consumed once. Since we are consuming this
  15. // once by cache and once by the browser for fetch, we need
  16. // to clone the request.
  17. var fetchRequest = event.request.clone();
  18.  
  19. // A cache hasn't been hit so we need to perform a fetch,
  20. // which makes a network request and returns the data if
  21. // anything can be retrieved from the network.
  22. return fetch(fetchRequest).then(
  23. function(response) {
  24. // Check if we received a valid response
  25. if(!response || response.status !== 200 || response.type !== 'basic') {
  26. return response;
  27. }
  28.  
  29. // Cloning the response since it's a stream as well.
  30. // Because we want the browser to consume the response
  31. // as well as the cache consuming the response, we need
  32. // to clone it so we have two streams.
  33. var responseToCache = response.clone();
  34.  
  35. caches.open(CACHE_NAME)
  36. .then(function(cache) {
  37. // Add the request to the cache for future queries.
  38. cache.put(event.request, responseToCache);
  39. });
  40.  
  41. return response;
  42. }
  43. );
  44. })
  45. );
  46. });
Add Comment
Please, Sign In to add comment