sw.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const CACHE_NAME = "1.2.3";
  2. const urlsToCache = [
  3. "/",
  4. "/manifest.json",
  5. "/images/favicon-32x32.png",
  6. "/images/favicon-16x16.png",
  7. "/apple-touch-icon.png",
  8. "/android-chrome-192x192.png",
  9. "/android-chrome-512x512.png",
  10. ];
  11. // Install event - cache resources
  12. self.addEventListener("install", (event) => {
  13. self.skipWaiting(); // 🔥 force install
  14. event.waitUntil(
  15. caches.open(CACHE_NAME).then((cache) => {
  16. return cache.addAll(urlsToCache);
  17. }),
  18. );
  19. });
  20. // Fetch event - network first with cache fallback
  21. self.addEventListener("fetch", (event) => {
  22. event.respondWith(
  23. fetch(event.request)
  24. .then((response) => {
  25. // If we get a valid response, clone it and update the cache
  26. if (response && response.status === 200) {
  27. const responseClone = response.clone();
  28. caches.open(CACHE_NAME).then((cache) => {
  29. cache.put(event.request, responseClone);
  30. });
  31. }
  32. return response;
  33. })
  34. .catch(() => {
  35. // If network fails, try to serve from cache
  36. return caches.match(event.request).then((cachedResponse) => {
  37. if (cachedResponse) {
  38. return cachedResponse;
  39. }
  40. // If no cache available, return a custom offline page or error
  41. if (event.request.destination === "document") {
  42. return new Response("Application hors ligne - Veuillez vérifier votre connexion internet", {
  43. status: 503,
  44. statusText: "Service Unavailable",
  45. headers: new Headers({
  46. "Content-Type": "text/html; charset=utf-8",
  47. }),
  48. });
  49. }
  50. });
  51. }),
  52. );
  53. });
  54. // Activate event - clean up old caches
  55. self.addEventListener("activate", (event) => {
  56. event.waitUntil(
  57. caches.keys().then((cacheNames) => {
  58. return Promise.all(
  59. cacheNames.map((cacheName) => {
  60. if (cacheName !== CACHE_NAME) {
  61. return caches.delete(cacheName);
  62. }
  63. }),
  64. );
  65. }),
  66. );
  67. self.clients.claim();
  68. });