PWA问题:更新服务工作者后清空缓存

问题描述

我是PWA的新手,正在接受一个简单项目的培训。第一次在goole chrome上运行后,一切正常,之后,我更改了service worker中的cacheName const和index.html中的标题,以测试所有站点资产的重新缓存。从这里开始,缓存仍然创建,但是它为空,并且出现错误“未捕获(承诺)TypeError:请求失败”,这是我们声明const staticCacheName ='site-static-v1'的SW行所引用的。

以下是SW的代码

const staticCacheName = 'site-static-v2';
const assets = [
    './','./index.html','./index.js','./main.js','./style.css','https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css','https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js','https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js','https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];

// install service worker
self.addEventListener('install',evt => {
    console.log('service worker has been installed');
    evt.waitUntil( 
        caches.open(staticCacheName).then(cache => {
            console.log('caching shell assets');
            cache.addAll(assets);
        })
    );
   
});

// activate event
self.addEventListener('activate',evt => {
    console.log('service worker has been activated');
});

// fetch event
self.addEventListener('fetch',evt => {
    evt.respondWith(
        caches.match(evt.request).then(cacheRes => {
            return cacheRes || fetch(evt.request);
        })
    );
});

任何帮助将不胜感激。

解决方法

问题出在您的资产阵列中。它仅将URLpath带到要缓存的文件,而不带文件路径。概括地说,删除这些路径前面的点。

const assets = [
    '/','/index.html','/index.js','/main.js','/style.css','https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css','https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js','https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js','https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];

如果要将js和css文件存储在以/ static为路由的静态文件夹中,则需要在其中存在的每个文件的前面添加/ static。

我想再次提到,它仅采用URLpath,而不采用FILEpath。它与您的文件路径无关。主要原因是实际上它从服务器而不是从计算机缓存资产。因此,它需要一个路由而不是文件路径。