Added automatic Rollwidth and Area Weigth selection by Article
This commit is contained in:
+197
-54
@@ -1,83 +1,226 @@
|
||||
// service-worker.js
|
||||
// Cache-Strategie: Cache First (offline works, then network)
|
||||
/**
|
||||
* SERVICE WORKER FOR NAUE ROLL CALCULATOR
|
||||
* ========================================
|
||||
* Caching strategy:
|
||||
* 1. CACHE_FIRST for static assets (CSS, JS, images)
|
||||
* 2. NETWORK_FIRST for API/data (with fallback to cache)
|
||||
* 3. STALE_WHILE_REVALIDATE for article data
|
||||
*/
|
||||
|
||||
const CACHE_NAME = 'roll-calculator-v3'; // bumped to v2 for new clearance settings
|
||||
const ASSETS_TO_CACHE = [
|
||||
'./',
|
||||
'./roll_calculator_v9.html',
|
||||
'./article-data.json',
|
||||
'./config.json',
|
||||
'./service-worker.js'
|
||||
const CACHE_NAME = 'rollcalc-v14-' + new Date().getTime();
|
||||
const STATIC_CACHE = 'rollcalc-static-v14';
|
||||
const DATA_CACHE = 'rollcalc-data-v14';
|
||||
|
||||
// Assets to cache on install
|
||||
const STATIC_ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/static/article-data.json',
|
||||
'/static/config.json'
|
||||
];
|
||||
|
||||
// Install Event
|
||||
// ===================================================================
|
||||
// INSTALL EVENT - Cache static assets
|
||||
// ===================================================================
|
||||
self.addEventListener('install', event => {
|
||||
console.log('[ServiceWorker] Installing...');
|
||||
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then(cache => {
|
||||
console.log('[ServiceWorker] Caching assets:', ASSETS_TO_CACHE);
|
||||
return cache.addAll(ASSETS_TO_CACHE);
|
||||
}).catch(err => {
|
||||
console.error('[ServiceWorker] Cache failed:', err);
|
||||
})
|
||||
caches.open(STATIC_CACHE)
|
||||
.then(cache => {
|
||||
console.log('[ServiceWorker] Caching static assets');
|
||||
return cache.addAll(STATIC_ASSETS).catch(err => {
|
||||
console.warn('[ServiceWorker] Some assets failed to cache:', err);
|
||||
// Don't fail installation if some assets can't be cached
|
||||
return Promise.resolve();
|
||||
});
|
||||
})
|
||||
.then(() => self.skipWaiting())
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
// Activate Event: Cleanup alte Caches
|
||||
// ===================================================================
|
||||
// ACTIVATE EVENT - Clean up old caches
|
||||
// ===================================================================
|
||||
self.addEventListener('activate', event => {
|
||||
console.log('[ServiceWorker] Activating...');
|
||||
|
||||
event.waitUntil(
|
||||
caches.keys().then(cacheNames => {
|
||||
return Promise.all(
|
||||
cacheNames.map(cacheName => {
|
||||
if (cacheName !== CACHE_NAME) {
|
||||
if (cacheName !== STATIC_CACHE &&
|
||||
cacheName !== DATA_CACHE &&
|
||||
cacheName !== CACHE_NAME) {
|
||||
console.log('[ServiceWorker] Deleting old cache:', cacheName);
|
||||
return caches.delete(cacheName);
|
||||
}
|
||||
})
|
||||
);
|
||||
})
|
||||
}).then(() => self.clients.claim())
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
// Fetch Event: Cache First Strategy
|
||||
// ===================================================================
|
||||
// FETCH EVENT - Intelligent caching strategy
|
||||
// ===================================================================
|
||||
self.addEventListener('fetch', event => {
|
||||
const url = event.request.url;
|
||||
|
||||
if (event.request.method !== 'GET') return;
|
||||
|
||||
event.respondWith(
|
||||
caches.match(event.request)
|
||||
.then(response => {
|
||||
if (response) {
|
||||
console.log('[ServiceWorker] Cache HIT:', url);
|
||||
return response;
|
||||
}
|
||||
console.log('[ServiceWorker] Cache MISS, fetching:', url);
|
||||
return fetch(event.request)
|
||||
.then(response => {
|
||||
if (!response || response.status !== 200 || response.type === 'error') {
|
||||
return response;
|
||||
const { request } = event;
|
||||
const url = new URL(request.url);
|
||||
|
||||
// Skip cross-origin requests
|
||||
if (url.origin !== location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 1. JSON DATA (article-data.json, config.json)
|
||||
// STALE_WHILE_REVALIDATE: Use cache first, update in background
|
||||
// ---------------------------------------------------------------
|
||||
if (url.pathname.includes('.json')) {
|
||||
event.respondWith(
|
||||
caches.open(DATA_CACHE).then(cache => {
|
||||
return cache.match(request).then(response => {
|
||||
const fetchPromise = fetch(request).then(networkResponse => {
|
||||
// Update cache with fresh version
|
||||
if (networkResponse && networkResponse.status === 200) {
|
||||
cache.put(request, networkResponse.clone());
|
||||
}
|
||||
const responseClone = response.clone();
|
||||
caches.open(CACHE_NAME).then(cache => {
|
||||
cache.put(event.request, responseClone);
|
||||
});
|
||||
return response;
|
||||
})
|
||||
.catch(() => {
|
||||
return caches.match(event.request).then(response => {
|
||||
if (response) return response;
|
||||
return new Response('Offline - resource not available', {
|
||||
status: 503,
|
||||
statusText: 'Service Unavailable'
|
||||
});
|
||||
});
|
||||
return networkResponse;
|
||||
}).catch(() => {
|
||||
// Network failed, return cached version
|
||||
return response || cacheNotFound('JSON data not found');
|
||||
});
|
||||
|
||||
// Return cached response immediately, update in background
|
||||
return response || fetchPromise;
|
||||
});
|
||||
})
|
||||
);
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 2. HTML PAGES
|
||||
// NETWORK_FIRST: Try network, fall back to cache
|
||||
// ---------------------------------------------------------------
|
||||
if (request.method === 'GET' &&
|
||||
(url.pathname === '/' || url.pathname.endsWith('.html'))) {
|
||||
event.respondWith(
|
||||
fetch(request)
|
||||
.then(response => {
|
||||
if (response && response.status === 200) {
|
||||
const cache_copy = response.clone();
|
||||
caches.open(STATIC_CACHE).then(cache => {
|
||||
cache.put(request, cache_copy);
|
||||
});
|
||||
}
|
||||
return response;
|
||||
})
|
||||
.catch(() => {
|
||||
return caches.match(request)
|
||||
.then(response => response || cacheNotFound('Page not found'));
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 3. STATIC ASSETS (CSS, JS, images)
|
||||
// CACHE_FIRST: Use cache if available, fall back to network
|
||||
// ---------------------------------------------------------------
|
||||
if (request.method === 'GET') {
|
||||
event.respondWith(
|
||||
caches.open(STATIC_CACHE).then(cache => {
|
||||
return cache.match(request).then(response => {
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
return fetch(request).then(networkResponse => {
|
||||
// Only cache successful responses
|
||||
if (networkResponse && networkResponse.status === 200) {
|
||||
cache.put(request, networkResponse.clone());
|
||||
}
|
||||
return networkResponse;
|
||||
}).catch(() => {
|
||||
// Return offline placeholder
|
||||
if (request.destination === 'image') {
|
||||
return createPlaceholderImage();
|
||||
}
|
||||
return cacheNotFound('Asset not found');
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// 4. POST/PUT/DELETE (API calls)
|
||||
// NETWORK_ONLY: Do not cache, but handle errors gracefully
|
||||
// ---------------------------------------------------------------
|
||||
if (['POST', 'PUT', 'DELETE'].includes(request.method)) {
|
||||
event.respondWith(
|
||||
fetch(request)
|
||||
.catch(() => {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: 'You are offline. API calls are not available.',
|
||||
status: 'offline'
|
||||
}),
|
||||
{
|
||||
status: 503,
|
||||
statusText: 'Service Unavailable',
|
||||
headers: new Headers({
|
||||
'Content-Type': 'application/json'
|
||||
})
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[ServiceWorker] Script loaded (v2)');
|
||||
// ===================================================================
|
||||
// HELPER FUNCTIONS
|
||||
// ===================================================================
|
||||
|
||||
function cacheNotFound(message) {
|
||||
return new Response(
|
||||
`<html><body style="font-family: sans-serif; padding: 20px; color: #666;">
|
||||
<h2>Offline</h2>
|
||||
<p>${message}</p>
|
||||
<p style="font-size: 12px; color: #999;">Roll Calculator is offline or the resource is not cached.</p>
|
||||
</body></html>`,
|
||||
{
|
||||
status: 404,
|
||||
statusText: 'Not Found',
|
||||
headers: new Headers({
|
||||
'Content-Type': 'text/html'
|
||||
})
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function createPlaceholderImage() {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
|
||||
<rect fill="#f0f0f0" width="100" height="100"/>
|
||||
<text x="50" y="50" text-anchor="middle" dy=".3em" fill="#999" font-size="12">
|
||||
Image offline
|
||||
</text>
|
||||
</svg>`;
|
||||
|
||||
return new Response(svg, {
|
||||
headers: {
|
||||
'Content-Type': 'image/svg+xml',
|
||||
'Cache-Control': 'public, max-age=86400'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// LOG SERVICE WORKER STATUS
|
||||
// ===================================================================
|
||||
console.log('[ServiceWorker] Naue Roll Calculator Service Worker loaded');
|
||||
|
||||
Reference in New Issue
Block a user