无法使用service-worker缓存简单的html文件

时间:2017-11-02 16:40:39

标签: javascript service-worker

我正在创建一个页面,当用户离线时会显示一条消息,但当我的服务工作者尝试缓存该页面时,总是会抛出Chrome控制台:

  

service-worker.js?v = 1:1 Uncaught(在promise中)DOMException:Quota   超标。 Promise被拒绝(异步)addEventListener.event @   ?服务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>

我已经删除了所有缓存,并且说“超出配额”,任何想法?

感谢。

1 个答案:

答案 0 :(得分:0)

如果您想在生产中使用服务工作者,我建议使用 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"
        }
    )