Service worker 为所有页面加载相同的html
我的Service worker 为所有页面加载相同的html,service-worker,progressive-web-apps,Service Worker,Progressive Web Apps,我的index.html文件中有一个应用程序外壳。我想为所有URL加载这个应用程序外壳,除了那些以/api/开头的URL(AJAX调用)。如何设置配置以实现此目的 service worker.js: (function() { 'use strict'; var filesToCache = [ '.', 'index.html', 'pwa-stylesheets/css/styles-new.css' ]; var staticCacheName = 'cac
index.html
文件中有一个应用程序外壳。我想为所有URL加载这个应用程序外壳,除了那些以/api/
开头的URL(AJAX调用)。如何设置配置以实现此目的
service worker.js:
(function() {
'use strict';
var filesToCache = [
'.',
'index.html',
'pwa-stylesheets/css/styles-new.css'
];
var staticCacheName = 'cache-v3';
self.addEventListener( 'install', function(event) {
event.waitUntil(
caches.open(staticCacheName)
.then(function(cache) {
return cache.addAll(filesToCache);
}).then( function() {
self.skipWaiting();
})
);
});
self.addEventListener( 'fetch', function(event) {
var url = event.request.url;
if( url.indexOf( "http://localhost:8080" ) > -1
&& url.indexOf( "http://localhost:8080/api/" ) == -1
&& url.indexOf( "http://localhost:8080/pwa-" ) == -1 ) {
// event.request.url = "http://localhost:8080/"; // not allowed
event.respondWith(
caches.match(event.request).then( function( response ) {
if( response ) {
console.log( 'Found ', url, ' in cache' );
return response;
}
console.log( 'Network request for ', url );
return fetch( event.request ).then( function( response ) {
if( ! response.ok ) {
console.log( "Network request failed." );
return null;
}
return caches.open( staticCacheName ).then( function(cache) {
cache.put(event.request.url, response.clone());
return response;
});
});
})
);
}
});
self.addEventListener('activate', function(event) {
var cacheWhitelist = [staticCacheName];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if( cacheWhitelist.indexOf(cacheName) === -1 ) {
return caches.delete(cacheName);
}
})
);
})
);
});
})();
您要做的是配置fetch事件处理程序以捕获或过滤api调用。当您看到对包含/api/的url的请求时,您将希望通过fetch调用访问网络。使用正则表达式检查请求URL,以应用API或任何其他URL所需的缓存策略。是的,我可以为所有API请求添加筛选器,这不是问题。但是,缓存api只有对event.request对象进行操作的get方法。不知何故,我必须将/、/link1、/link2映射到同一个index.html文件,然后您需要捕获这些请求URL,并在服务器工作者中创建自己的响应对象。这类似于具有回退响应逻辑。查看通用的回退策略-您需要根据自己的需要对其进行一些修改。