[英]Can't cache simple html file with service-worker
我正在創建一個頁面,當用戶離線時顯示一條消息,但當我的服務工作者嘗試緩存頁面時,總是會拋出Chrome控制台:
service-worker.js?v = 1:1未捕獲(在promise中)DOMException:超出配額。 Promise被拒絕(異步)addEventListener.event @ service-worker.js?v = 1:10
服務人員注冊:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./assets/app/js/service-worker.js?v=1').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});}
服務工作者:
'use strict';
var cacheVersion = 1;
var currentCache = {
offline: 'offline-cache' + cacheVersion
};
var offlineUrl = '../../../offline.html';
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache.offline).then(function (cache) {
return cache.addAll([
offlineUrl
]);
})
);
});
this.addEventListener('fetch', event => {
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
return caches.match(offlineUrl);
})
);
}
else {
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
offline.html:
<div> offline test </div>
我已經刪除了所有緩存,並且說“超出配額”,任何想法?
謝謝。
如果你想在生產中使用服務工作者,我建議使用sw-precache插件(用於gulp或web pack)或工作箱 。 之后,您可以在bundler中設置緩存文件URL。 來自真實項目的webpack和sw-precache示例:
new SWPrecacheWebpackPlugin(
{
cacheId: "static-cache",
filepath: __dirname + "/app/public/sw.js",
stripPrefix: __dirname + "/app/public/",
replacePrefix: "/",
staticFileGlobs: [
__dirname + "/app/public/dist/**/*.{js,html,css,eot,ttf,woff,woff2}",
__dirname + "/app/public/img/**/*.{png,jpg,gif,svg}",
__dirname + '/app/public/offline.html' /* here you can set offline urls*/
],
navigateFallback: __dirname + "/app/public/index.html"
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.