1 | const SCOPE="/fonts/"
|
2 | self.addEventListener("message", function({data:{familyName, src, scope}}){
|
3 | if(familyName && src){
|
4 | self.caches.open("v1").then(cache=>{
|
5 | return fetch(src).then(response=>{
|
6 | cache.put(SCOPE+familyName,response.clone())
|
7 | })
|
8 | })
|
9 | }
|
10 | })
|
11 |
|
12 | self.addEventListener("fetch", function(e){
|
13 | const path=new URL(e.request.url).pathname
|
14 | if(!(path+"/").startsWith(SCOPE)){
|
15 | return
|
16 | }
|
17 |
|
18 | return e.respondWith(self.caches.match(e.request.url).then(function(cached){
|
19 | if((path+"/")==SCOPE){
|
20 | return fetch(e.request).then(function(response){
|
21 | if(!response.ok){
|
22 | if(cached){
|
23 | return cached.clone().text()
|
24 | }else{
|
25 | return Promise.resolve("")
|
26 | }
|
27 | }
|
28 | return response.text()
|
29 | })
|
30 | .then(fonts=>{
|
31 | fonts=new Set(fonts.split(",").filter(a=>!!a))
|
32 | return self.caches.open("v1")
|
33 | .then(cache=>cache.keys())
|
34 | .then(cached=>{
|
35 | cached.forEach(a=>{
|
36 | const path=new URL(a.url).pathname
|
37 | if(path.startsWith(SCOPE)){
|
38 | const name=path.split("/").pop()
|
39 | if(name && name!="index.html"){
|
40 | fonts.add(name)
|
41 | }
|
42 | }
|
43 | })
|
44 | return Array.from(fonts)
|
45 | })
|
46 | })
|
47 | .then(fonts=>new Response(fonts.join(",")))
|
48 | }
|
49 |
|
50 | return cached||fetch(e.request)
|
51 | }))
|
52 | })
|