你可以尝试这样的事情:
var CACHE_NAME = 'dependencies-cache';
self.addEventListener('install', function(event) {
console.log('[install] Kicking off service worker registration!');
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) { // With the cache opened, load a JSON file containing an array of files to be cached
return fetch('files-to-cache.json').then(function(response) {
return response.json(); // Once the contents are loaded, convert the raw text to a JavaScript object
}).then(function(files) {
console.log('[install] Adding files from JSON file: ', files); // this will log the cached json file
return cache.addAll(files); // Use cache.addAll just as you would a hardcoded array of items
});
})
.then(function() {
console.log(
'[install] All required resources have been cached;',
'the Service Worker was successfully installed!'
);
return self.skipWaiting(); // Force activation
})
);
});
这将解决您的问题。从上面的代码中,您可以简单地返回响应response.json()
,将原始文本转换为 Javascript 对象。有关 Service Worker 缓存 JSON 文件的完整实现,您可以访问此文档。