Я слежу за веб-сайтом, на котором есть сервисный работник. Теперь я столкнулся с проблемой: после обновления изображения, изменения файла serviceworker и подтверждения того, что изображение было изменено путем принудительного обновления в Service Worker, изображение не изменилось в Safari или Chrome через 2 дня.
Изображение представляет собой замену с тем же именем файла, HTML не был изменен. Я знаю, что могу исправить это, изменив имя файла изображения, но мне хотелось бы знать, как это сделать в сервисном работнике.
Код ПО:
// Thanks Jeremy Keith https://adactio.com/serviceworker.js
'use strict';
const version = 'v6';
const staticCacheName = version + 'static';
const pagesCacheName = 'pages';
const imagesCacheName = 'images';
const maxPages = 50; // Maximum number of pages to cache
const maxImages = 100; // Maximum number of images to cache
const timeout = 3000; // Number of milliseconds before timing out
const cacheList = [
staticCacheName,
pagesCacheName,
imagesCacheName
];
function updateStaticCache() {
return caches.open(staticCacheName)
.then( staticCache => {
// These items won't block the installation of the Service Worker
staticCache.addAll([
'images/facebook.webp',
'/images/derek.avif',
'/images/instagram.webp',
'/images/messenger.svg',
'/images/whatsapp.svg',
'/images/one-one-pt.avif',
'/images/sport-specific-pt.avif',
'/images/knockout-fitness.avif',
'/images/in-depth-flexibility-mobility.avif',
'/fonts/barlow-light-webfont.woff2',
'/fonts/barlow-lightitalic-webfont.woff2',
'/fonts/barlow-regular-webfont.woff2',
'/fonts/barlow-semibold-webfont.woff2'
]);
// These items must be cached for the Service Worker to complete installation
return staticCache.addAll([
'/js/main.js?' + version,
'/js/contact.js?' + version,
]);
});
}
// Cache the page(s) that initiate the service worker
function cacheClients() {
const pages = [];
return clients.matchAll({
includeUncontrolled: true
})
.then( allClients => {
for (const client of allClients) {
pages.push(client.url);
}
})
.then ( () => {
caches.open(pagesCacheName)
.then( pagesCache => {
return pagesCache.addAll(pages);
});
})
}
// Remove caches whose name is no longer valid
function clearOldCaches() {
return caches.keys()
.then( keys => {
return Promise.all(keys
.filter(key => !cacheList.includes(key))
.map(key => caches.delete(key))
);
});
}
function trimCache(cacheName, maxItems) {
caches.open(cacheName)
.then( cache => {
cache.keys()
.then(keys => {
if (keys.length > maxItems) {
cache.delete(keys[0])
.then( () => {
trimCache(cacheName, maxItems)
});
}
});
});
}
addEventListener('install', event => {
event.waitUntil(
updateStaticCache()
.then( () => {
cacheClients()
})
.then( () => {
return skipWaiting();
})
);
});
addEventListener('activate', event => {
event.waitUntil(
clearOldCaches()
.then( () => {
return clients.claim();
})
);
});
if (registration.navigationPreload) {
addEventListener('activate', event => {
event.waitUntil(
registration.navigationPreload.enable()
);
});
}
self.addEventListener('message', event => {
if (event.data.command == 'trimCaches') {
trimCache(pagesCacheName, maxPages);
trimCache(imagesCacheName, maxImages);
}
});
addEventListener('fetch', event => {
const request = event.request;
// Ignore localhost as it's a PITA when developing
if(request.url.includes('localhost')) {
return;
}
// Ignore non-GET requests
if(request.method !== 'GET') {
return;
}
// Ignore third parties
if(!request.url.includes('jordanjohnson.pt')) {
return;
}
const retrieveFromCache = caches.match(request);
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.mode === 'navigate' || request.headers.get('Accept').includes('text/html')) {
event.respondWith(
new Promise( resolveWithResponse => {
const timer = setTimeout( () => {
// Time out: CACHE
retrieveFromCache
.then( responseFromCache => {
if (responseFromCache) {
resolveWithResponse(responseFromCache);
}
})
}, timeout);
Promise.resolve(event.preloadResponse)
.then( preloadResponse => preloadResponse || fetch(request) )
.then( responseFromPreloadOrFetch => {
// NETWORK
clearTimeout(timer);
const copy = responseFromPreloadOrFetch.clone();
// Stash a copy of this page in the pages cache
try {
event.waitUntil(
caches.open(pagesCacheName)
.then( pagesCache => {
return pagesCache.put(request, copy);
})
);
} catch (error) {
console.error(error);
}
resolveWithResponse(responseFromPreloadOrFetch);
})
.catch( preloadOrFetchError => {
clearTimeout(timer);
console.error(preloadOrFetchError, request);
// CACHE or FALLBACK
retrieveFromCache
.then( responseFromCache => {
resolveWithResponse(
responseFromCache || caches.match('/offline/')
);
});
});
})
)
return;
}
// For non-HTML requests, look in the cache first, fall back to the network
event.respondWith(
retrieveFromCache
.then(responseFromCache => {
// CACHE
return responseFromCache || fetch(request)
.then( responseFromFetch => {
// NETWORK
// If the request is for an image, stash a copy of this image in the images cache
if (request.url.match(/\.(jpe?g|avif|webp)/)) {
const copy = responseFromFetch.clone();
try {
event.waitUntil(
caches.open(imagesCacheName)
.then( imagesCache => {
return imagesCache.put(request, copy);
})
);
} catch (error) {
console.error(error);
}
}
return responseFromFetch;
})
.catch( fetchError => {
console.error(fetchError);
// FALLBACK
// show an offline placeholder
if (request.url.match(/\.(jpe?g|webp|avif)/)) {
return new Response('Offlineoffline', {headers: {'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store'}});
}
});
})
);
});
Подробнее здесь: https://stackoverflow.com/questions/797 ... on-website
Работник службы предотвращает обновление изображений на веб-сайте [закрыто] ⇐ Javascript
Форум по Javascript
1760719640
Anonymous
Я слежу за веб-сайтом, на котором есть сервисный работник. Теперь я столкнулся с проблемой: после обновления изображения, изменения файла serviceworker и подтверждения того, что изображение было изменено путем принудительного обновления в Service Worker, изображение не изменилось в Safari или Chrome через 2 дня.
Изображение представляет собой замену с тем же именем файла, HTML не был изменен. Я знаю, что могу исправить это, изменив имя файла изображения, но мне хотелось бы знать, как это сделать в сервисном работнике.
Код ПО:
// Thanks Jeremy Keith https://adactio.com/serviceworker.js
'use strict';
const version = 'v6';
const staticCacheName = version + 'static';
const pagesCacheName = 'pages';
const imagesCacheName = 'images';
const maxPages = 50; // Maximum number of pages to cache
const maxImages = 100; // Maximum number of images to cache
const timeout = 3000; // Number of milliseconds before timing out
const cacheList = [
staticCacheName,
pagesCacheName,
imagesCacheName
];
function updateStaticCache() {
return caches.open(staticCacheName)
.then( staticCache => {
// These items won't block the installation of the Service Worker
staticCache.addAll([
'images/facebook.webp',
'/images/derek.avif',
'/images/instagram.webp',
'/images/messenger.svg',
'/images/whatsapp.svg',
'/images/one-one-pt.avif',
'/images/sport-specific-pt.avif',
'/images/knockout-fitness.avif',
'/images/in-depth-flexibility-mobility.avif',
'/fonts/barlow-light-webfont.woff2',
'/fonts/barlow-lightitalic-webfont.woff2',
'/fonts/barlow-regular-webfont.woff2',
'/fonts/barlow-semibold-webfont.woff2'
]);
// These items must be cached for the Service Worker to complete installation
return staticCache.addAll([
'/js/main.js?' + version,
'/js/contact.js?' + version,
]);
});
}
// Cache the page(s) that initiate the service worker
function cacheClients() {
const pages = [];
return clients.matchAll({
includeUncontrolled: true
})
.then( allClients => {
for (const client of allClients) {
pages.push(client.url);
}
})
.then ( () => {
caches.open(pagesCacheName)
.then( pagesCache => {
return pagesCache.addAll(pages);
});
})
}
// Remove caches whose name is no longer valid
function clearOldCaches() {
return caches.keys()
.then( keys => {
return Promise.all(keys
.filter(key => !cacheList.includes(key))
.map(key => caches.delete(key))
);
});
}
function trimCache(cacheName, maxItems) {
caches.open(cacheName)
.then( cache => {
cache.keys()
.then(keys => {
if (keys.length > maxItems) {
cache.delete(keys[0])
.then( () => {
trimCache(cacheName, maxItems)
});
}
});
});
}
addEventListener('install', event => {
event.waitUntil(
updateStaticCache()
.then( () => {
cacheClients()
})
.then( () => {
return skipWaiting();
})
);
});
addEventListener('activate', event => {
event.waitUntil(
clearOldCaches()
.then( () => {
return clients.claim();
})
);
});
if (registration.navigationPreload) {
addEventListener('activate', event => {
event.waitUntil(
registration.navigationPreload.enable()
);
});
}
self.addEventListener('message', event => {
if (event.data.command == 'trimCaches') {
trimCache(pagesCacheName, maxPages);
trimCache(imagesCacheName, maxImages);
}
});
addEventListener('fetch', event => {
const request = event.request;
// Ignore localhost as it's a PITA when developing
if(request.url.includes('localhost')) {
return;
}
// Ignore non-GET requests
if(request.method !== 'GET') {
return;
}
// Ignore third parties
if(!request.url.includes('jordanjohnson.pt')) {
return;
}
const retrieveFromCache = caches.match(request);
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.mode === 'navigate' || request.headers.get('Accept').includes('text/html')) {
event.respondWith(
new Promise( resolveWithResponse => {
const timer = setTimeout( () => {
// Time out: CACHE
retrieveFromCache
.then( responseFromCache => {
if (responseFromCache) {
resolveWithResponse(responseFromCache);
}
})
}, timeout);
Promise.resolve(event.preloadResponse)
.then( preloadResponse => preloadResponse || fetch(request) )
.then( responseFromPreloadOrFetch => {
// NETWORK
clearTimeout(timer);
const copy = responseFromPreloadOrFetch.clone();
// Stash a copy of this page in the pages cache
try {
event.waitUntil(
caches.open(pagesCacheName)
.then( pagesCache => {
return pagesCache.put(request, copy);
})
);
} catch (error) {
console.error(error);
}
resolveWithResponse(responseFromPreloadOrFetch);
})
.catch( preloadOrFetchError => {
clearTimeout(timer);
console.error(preloadOrFetchError, request);
// CACHE or FALLBACK
retrieveFromCache
.then( responseFromCache => {
resolveWithResponse(
responseFromCache || caches.match('/offline/')
);
});
});
})
)
return;
}
// For non-HTML requests, look in the cache first, fall back to the network
event.respondWith(
retrieveFromCache
.then(responseFromCache => {
// CACHE
return responseFromCache || fetch(request)
.then( responseFromFetch => {
// NETWORK
// If the request is for an image, stash a copy of this image in the images cache
if (request.url.match(/\.(jpe?g|avif|webp)/)) {
const copy = responseFromFetch.clone();
try {
event.waitUntil(
caches.open(imagesCacheName)
.then( imagesCache => {
return imagesCache.put(request, copy);
})
);
} catch (error) {
console.error(error);
}
}
return responseFromFetch;
})
.catch( fetchError => {
console.error(fetchError);
// FALLBACK
// show an offline placeholder
if (request.url.match(/\.(jpe?g|webp|avif)/)) {
return new Response('Offlineoffline', {headers: {'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store'}});
}
});
})
);
});
Подробнее здесь: [url]https://stackoverflow.com/questions/79793268/service-worker-preventing-image-updating-on-website[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия