[英]Progressive Web App - Service Worker not serving start_URL
[英]Avoid caching start_url with service worker
我在為網站設置服務人員時遇到一些問題。
我只想緩存css / js / fonts和一些圖像/ svg,我不想緩存HTML,因為所有內容每分鍾都會更新。
有點用,但是即使在我已經添加了智能手機的情況下,我仍然嘗試在智能手機上不斷收到“添加到主屏幕”通知。 在Chrome Dev應用程序上,我沒有“添加”按鈕。
同樣,在Lighthouse上,我得到以下錯誤:
“脫機時不響應200”
“不會提示用戶安裝Web應用程序,失敗:Service Worker不會緩存清單start_url。”
現在我的sw.js就是這樣。 如您所見,我評論了fetch部分,因為它正在緩存HTML,並且Cookies也不起作用。
是否有一個簡單的Service Worker“模板”可供使用?
const PRECACHE = 'app-name';
const RUNTIME = 'runtime';
// A list of local resources we always want to be cached.
const PRECACHE_URLS = [
'/css/file.css',
'/js/file.js',
'/images/logo.png',
'/fonts/roboto/Roboto-Regular.woff2'
]
// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting())
);
});
// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim())
);
});
// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
// Skip cross-origin requests, like those for Google Analytics.
// if (event.request.url.startsWith(self.location.origin)) {
// event.respondWith(
// caches.match(event.request).then(cachedResponse => {
// if (cachedResponse) {
// return cachedResponse;
// }
// return caches.open(RUNTIME).then(cache => {
// return fetch(event.request).then(response => {
// // Put a copy of the response in the runtime cache.
// return cache.put(event.request, response.clone()).then(() => {
// return response;
// });
// });
// });
// })
// );
// }
});
我不確定為什么會出現安裝橫幅,但是lighthouse給出的兩個錯誤與缺少start_url(可能是index.html)的緩存有關。 因此,如果您遵循此處介紹的緩存策略,那么Lighthouse將始終告訴您有關這些內容的信息。
我建議您可以嘗試Workbox及其運行時緩存。 簡而言之,運行時緩存的工作原理是這樣的:您指定諸如* .svg,*。css等的url,一旦客戶端首次詢問它們,SW就會對其進行緩存。 將來,當文件已經被緩存時,SW將從緩存中將它們提供給客戶端。 基本上,您告訴SW 在遇到此類URL 時緩存它們,而不是事先緩存它們 。
運行時緩存可能很好地伴隨着預緩存(也可以從Workbox中找到)來緩存一堆文件。
在這里查看: https : //workboxjs.org
他們有一些用於構建工具的示例和插件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.