Skip to content

Instantly share code, notes, and snippets.

@marcoscaceres
Last active September 2, 2015 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoscaceres/c90970c16123a28c5a93 to your computer and use it in GitHub Desktop.
Save marcoscaceres/c90970c16123a28c5a93 to your computer and use it in GitHub Desktop.
CacheTask for service workers
const CacheTasks = {
/**
* Populates the a cache with a list of requests.
*
* @param {String} cacheName The name of the cache.
* @param {Array} requests The requests (URLs or Requests) to cache.
*/
populateCache: async(function* (cacheName, requests) {
var cache = yield caches.open(name);
try {
yield cache.addAll(requests);
} catch (err) {
var msg = `Problem adding resources to cache ${cacheName}`;
console.warn(msg, err);
}
}),
/**
* Saves a binary file into a cache.
*
* @param {String} cacheName The name of the cache to save into.
* @param {ArrayBuffer} arrayBuffer The arrayBuffer holding the file's data.
* @param {String} type MimeType of the data being stored.
*/
saveBinaryToCache: async(function* (cacheName, arrayBuffer, type, aRequestURL) {
var cache = yield caches.open(cacheName);
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], {
type
});
var responseInit = {
headers: {
"Content-Type": type
}
};
var request = new Request(aRequestURL);
var response = new Response(blob, responseInit);
var success = true;
try {
yield cache.put(request, response);
} catch (err) {
var msg = `Error putting blob in cache ${cacheName}`;
console.warn(msg, err);
success = false;
}
return success;
}),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment