File size: 3,768 Bytes
3253fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const CACHE_NAME = 'teplostil-cache-v5'; // Обновляем версию кэша
const URLS_TO_CACHE = [
    '/',
    '/index.html',
    '/style.css',
    '/icon.png',
    '/icon-512x512.png',
    '/manifest.json'
];

// Установка Service Worker и кэширование ресурсов
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            console.log('Opened cache');
            return cache.addAll(URLS_TO_CACHE);
        })
    );
    self.skipWaiting();
});

// Активация и удаление старых кэшей
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        console.log('Deleting old cache:', cacheName);
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
    self.clients.claim();
});

// Обработка запросов
self.addEventListener('fetch', (event) => {
    const requestUrl = new URL(event.request.url);

    // Пропускаем запросы к внешнему iframe.  Кэшируем их стандартным образом браузера.
    if (requestUrl.origin !== self.location.origin) {
        console.log('Пропускаем внешний запрос (не кэшируем через SW):', requestUrl.href);
        // Используем стандартный fetch, не вмешиваясь.  Браузер сам разберется с кэшированием.
        return;
    }

    // Для навигационных запросов (это запросы к index.html)
    if (event.request.mode === 'navigate') {
        event.respondWith(
            caches.match('/index.html').then((response) => {
                return response || fetch(event.request);
            })
        );
    } else {
        // Для локальных ресурсов используем Cache First
        event.respondWith(
            caches.match(event.request).then((response) => {
                // Возвращаем кэшированный ресурс, если есть.
                if (response) {
                    return response;
                }

                // Если ресурса нет в кэше, делаем сетевой запрос.
                return fetch(event.request).then((networkResponse) => {
                    // Если запрос с нашего origin, кэшируем ответ.
                    if (requestUrl.origin === self.location.origin) {
                        return caches.open(CACHE_NAME).then((cache) => {
                            cache.put(event.request, networkResponse.clone());
                            return networkResponse;
                        });
                    }
                    // Если запрос не с нашего origin, просто возвращаем ответ (не кэшируем в SW).
                    return networkResponse;
                });
            }).catch(error => {
                // Обработка ошибок, если и кэш недоступен, и сеть.
                console.error("Fetch failed:", error);
                // Можно вернуть страницу-заглушку об ошибке.
                return new Response('<h1>Offline</h1><p>Sorry, the content is not available offline.</p>', {
                    headers: { 'Content-Type': 'text/html' }
                });

            })
        );
    }
});