我有域https://test.com。以下是我的服务工作者代码
var CACHE_NAME = 'my-site-mas2';
var urlsToCache = [
'/',
'/scripts/app.js',
'/scripts/test.js',
'/scripts/test1.js',
'/scripts/test2.js',
'https://otherdomain.com/planet-styles.min.css'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// var corsRequest = new Request(url, { mode: 'cors' });
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
self.addEventListener('activate', function(event) {
var cacheWhitelist = ['my-site-mas2'];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
我需要缓存跨域声明。上面的代码抛出 无法加载https://otherdomain.com/planet-styles.min.css:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“https://test.com”访问。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取已禁用CORS的资源。