1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 | |
16 | |
17 | |
18 | const VERSION = "1.00" |
19 | |
20 | |
21 | const CACHE = "ejemploPWA" |
22 | |
23 | |
24 | |
25 | |
26 | |
27 | const ARCHIVOS = [ |
28 | "favicon.ico", |
29 | "index.html", |
30 | "site.webmanifest", |
31 | "css/estilos.css", |
32 | "img/icono2048.png", |
33 | "img/maskable_icon.png", |
34 | "img/maskable_icon_x128.png", |
35 | "img/maskable_icon_x192.png", |
36 | "img/maskable_icon_x384.png", |
37 | "img/maskable_icon_x48.png", |
38 | "img/maskable_icon_x512.png", |
39 | "img/maskable_icon_x72.png", |
40 | "img/maskable_icon_x96.png", |
41 | "img/screenshot_horizontal.png", |
42 | "img/screenshot_vertical.png", |
43 | "js/registraServiceWorker.js", |
44 | "/" |
45 | ] |
46 | |
47 | |
48 | if (self instanceof ServiceWorkerGlobalScope) { |
49 | |
50 | self.addEventListener("install", |
51 | ( evt) => { |
52 | console.log("El service worker se está instalando.") |
53 | evt.waitUntil(llenaElCache()) |
54 | }) |
55 | |
56 | |
57 | self.addEventListener("fetch", ( evt) => { |
58 | if (evt.request.method === "GET") { |
59 | evt.respondWith(buscaLaRespuestaEnElCache(evt)) |
60 | } |
61 | }) |
62 | |
63 | |
64 | self.addEventListener("activate", |
65 | () => console.log("El service worker está activo.")) |
66 | } |
67 | |
68 | async function llenaElCache() { |
69 | console.log("Intentando cargar caché:", CACHE) |
70 | |
71 | const keys = await caches.keys() |
72 | for (const key of keys) { |
73 | await caches.delete(key) |
74 | } |
75 | |
76 | const cache = await caches.open(CACHE) |
77 | |
78 | await cache.addAll(ARCHIVOS) |
79 | console.log("Cache cargado:", CACHE) |
80 | console.log("Versión:", VERSION) |
81 | } |
82 | |
83 | |
84 | async function buscaLaRespuestaEnElCache(evt) { |
85 | |
86 | const cache = await caches.open(CACHE) |
87 | const request = evt.request |
88 | |
89 | |
90 | const response = await cache.match(request, { ignoreSearch: true }) |
91 | if (response === undefined) { |
92 | |
93 | |
94 | return fetch(request) |
95 | } else { |
96 | |
97 | return response |
98 | } |
99 | } |