Last active
August 18, 2018 11:33
-
-
Save Yaffle/40c58eb0c8075949313b3348bbb5f2b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint strict:global*/ | |
/*global self, fetch, caches, console, Promise, Request*/ | |
"use strict"; | |
var CACHE_NAME_PREFIX = "ru~"; | |
var CACHE_NAME = "ru~20180818T075107Z"; | |
var URLS_TO_CACHE = "./;js.js?20180818T075107Z;css.css?20180818T075107"; | |
self.addEventListener("install", function (event) { | |
console.log("install", CACHE_NAME); | |
event.waitUntil(caches.open(CACHE_NAME).then(function (cache) { | |
return Promise.all(URLS_TO_CACHE.split(";").map(function (requestURL) { | |
var request = new Request(requestURL); | |
// I have added {cache: "no-cache"} option later. | |
return fetch(request.clone()).then(function (response) { | |
if (response.status >= 200 && response.status <= 299 && response.type === "basic") { | |
return cache.put(request, response.clone()); | |
} | |
return Promise.reject(new Error()); | |
}); | |
})); | |
})); | |
}); | |
self.addEventListener("activate", function (event) { | |
console.log("activate", CACHE_NAME); | |
event.waitUntil(caches.keys().then(function (cacheNames) { | |
return Promise.all(cacheNames.map(function (cacheName) { | |
if (cacheName.slice(0, CACHE_NAME_PREFIX.length) !== CACHE_NAME_PREFIX) { | |
return undefined; | |
} | |
if (cacheName === CACHE_NAME) { | |
return undefined; | |
} | |
return caches["delete"](cacheName); | |
})); | |
})); | |
}); | |
self.addEventListener("fetch", function (event) { | |
var request = event.request; | |
var requestURL = request.url; | |
event.respondWith(caches.open(CACHE_NAME).then(function (cache) { | |
return cache.match(request).then(function (response) { | |
if (response != undefined) { | |
console.log("cache.match", CACHE_NAME, requestURL); | |
return response; | |
} | |
return fetch(request.clone()); | |
}); | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment