I am trying to do some performance improvements for our web app by using web workers. I need to include some scripts that I was using importScripts(). But the conundrum is that importScripts fails when trying to access offline. How do I access these files offline using Cache API? Do I need to implement custom reader for reading ReadableStream? Is there a better standard to implement offline cache access inside web workers?
Details
These files are javascript scripts which have some custom js and external libraries like CryptoJS and LocalForage. I would like to implement - Network falling back to Cache paradigm using CacheAPI/Service Workers.
I initially implemented a standard Service Worker with an install and fetch event listeners but I believe the scope between the service worker and the web worker was not the same. After some research on MDN and exploration, I see that Cache API is available within the WebWorkerScope so I moved the cache call within the web worker scope.
I have tried various ways of accessing these files by using fetch events and just getting the files from cache. I get a response back after my promises resolve but the body of the response is a readable stream and I am not sure how to resolve that.
Any help or pointers would be really appreciated.
My web worker invocation
var worker = new Worker('Path');
I have attempted to follow the write up as a guide - https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker
// Web Worker
self.addEventListener('fetch', function(event){
event.respondWith(
fetch(event.request).catch(function(){
return caches.match(event.request);
})
)
});
caches.open('mcaseworker').then(function(cache){
var urlList = ['/resources/scripts/custom/globalConfig.js',
'/resources/scripts/localforage/localforage.min.js'
'/resources/scripts/utility/pako.js',
'/resources/scripts/cryptojs/aes.js',
'/resources/scripts/cryptojs/sha1.js'
];
// Initialize a promise all with the list of urls
Promise.all(urlList.map(function(url){
return fetch(url, {
headers : {
'Content-Type' : 'application/x-javascript'
}
})
.then(function(response){
if (response){
return response;
}
});
}))
.then(function(values){
Promise.all(values.map(function(value){
return value;
}))
.then(function(res){
// Custom Code
// Would like to access localforage and other javascript libraries.
})
})
})