我想添加服务工作者以在应用程序中缓存加载的资源。
想象一下 我的应用程序正在https://domain/application
下加载从该/ application页面中,我正在从服务器别名中获取资源, https://domain/mat-resources/applications/application1/dist/ ..
这是我的寄存器,
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/mat-resources/applications/application1/
/service-worker.js', {scope: '/mat-resources/applications/application1/'}).then(function (registration) {
console.log("registration", registration);
}).catch(function (e) {
console.log(e);
});
} else {
console.log('Service Worker is not supported in this browser.')
}
这是我添加到服务工作者js中的代码
'use strict';
const VERSION = 'v1';
const PRECACHE = `precache-${VERSION}`;
const RUNTIME = `runtime-${VERSION}`;
const enableRuntimeCache = true;
const mode = 'cache-update';
const PRECACHE_URLS = [
'https://fonts.googleapis.com/css?family=Open+Sans:400,600|Roboto:400,500',
'./dist/js/vendor.bundle.js',
'./dist/js/app.bundle.js',
'./dist/css/styles.min.css'
];
let NetworkOnline = true;
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE).then(cache => {
cache.addAll(PRECACHE_URLS);
}).then(self.skipWaiting())
);
});
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();
})
);
});
self.addEventListener('fetch', event => {
if (event.request.url.startsWith(self.location.origin)) {
event.respondWith(fromCache(event.request));
if (isOnline()) {
if (mode === 'cache-update') {
event.waitUntil(
update(event.request)
/*.then(refresh)*/
.catch(errorHandler)
);
}
}
}
});
/*function setFromCache(request) {
console.log(self);
updateFromCache(true);
}*/
function fromCache(request) {
return caches.match(request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
if (isOnline()) {
if (enableRuntimeCache) {
return caches.open(RUNTIME).then(cache => {
return fetch(request).then(response => {
return cache.put(request, response.clone()).then(() => {
return response;
});
}).catch(errorHandler);
});
} else {
return fetch(request).then(response => {
return response;
});
}
}
});
}
function update(request) {
let asset = request.url.substr(request.url.lastIndexOf('/') + 1);
let openCache = (PRECACHE_URLS.some(val => val.indexOf(asset) >= 0)) ? PRECACHE : RUNTIME;
return caches.open(openCache).then(cache => {
return fetch(`${request.url }?${new Date().valueOf()}`).then(response => {
return cache.put(request, response.clone()).then(() => {
return response;
});
}).catch(errorHandler);
});
}
function refresh(response) {
return self.clients.matchAll().then(clients => {
clients.forEach(client => {
var message = {
type: 'refresh',
url: response.url,
eTag: response.headers.get('ETag')
};
client.postMessage(JSON.stringify(message));
});
});
}
function isOnline() {
return self.navigator.onLine;
}
function errorHandler(error) {
if (error instanceof TypeError) {
if (error.message.includes('Failed to fetch')) {
console.error('(FtF) Error caught:', error);
} else {
console.error('Error caught:', error);
}
}
}
成功刷新服务程序后,我可以看到服务程序已正确注册,但是资源没有被占用。
请帮助?
答案 0 :(得分:0)
注册服务工作者时已定义范围。这限制了服务工作者只能访问针对/mat-resources/applications/application1/**/*
路径下资源的提取
{scope: '/mat-resources/applications/application1/'}
如果您希望服务人员在应用程序/application
的根目录处理资源,则需要将范围设置为/
。
{scope: '/'}
您可以在Web Fundamentals上了解有关范围的更多信息。