cache images/* on PWA installation
Hunter
Friday, July 11th, 2025 at 5:00 PM
-const CACHE_NAME = 'web-workshop-v2';
1 +const CACHE_NAME = 'web-workshop-v3';
2 const urlsToCache = [
3 '/',
4 '/index.html',
44 }
45 }
46
47 +// Function to programmatically cache all images
48 +async function cacheImages(cache) {
49 + const imageExtensions = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'];
50 +
51 + try {
52 + const response = await fetch('/images/');
53 + if (response.ok) {
54 + const html = await response.text();
55 + const imagePattern = new RegExp(`href="([^"]*\\.(${imageExtensions.join('|')}))"`, 'gi');
56 + const links = html.match(imagePattern);
57 +
58 + if (links) {
59 + const imageFiles = links.map(link => {
60 + const match = link.match(/href="([^"]*)"/);
61 + return match ? '/images/' + match[1] : null;
62 + }).filter(Boolean);
63 +
64 + for (const imageFile of imageFiles) {
65 + try {
66 + await cache.add(imageFile);
67 + console.log(`Cached image: ${imageFile}`);
68 + } catch (e) {
69 + console.log(`Failed to cache image ${imageFile}:`, e);
70 + }
71 + }
72 + }
73 + }
74 + } catch (e) {
75 + console.log('Failed to cache images directory:', e);
76 + }
77 +}
78 +
79 // Install service worker and cache resources
80 self.addEventListener('install', event => {
81 event.waitUntil(
95 }
96 }
97
- // Cache directory files
- await cacheDirectoryFiles(cache, ['/images/', '/pages/']);
98 + // Cache all images programmatically
99 + await cacheImages(cache);
100 })
101 .then(() => self.skipWaiting())
102 );