1.0.0 • Published 9 years ago
chialab-resources-cache v1.0.0
Resources Cache
Cache resources like images, texts, html pages and more!
Install
$ npm i chialab-resources-cache --save
$ bower i chialab-resources-cache --save
Polyfill
This library relies on Fetch API and Cache API.
If your target may not support those specs, you can add:
- whatwg-fetch polyfill for Fetch API.
- chialab-graceful-cache adapter for Cache API.
Documentation
Quick use
Cache an image:
const cacheName = '__local';
const imageUrl = 'http://www.chialab.it/img/pesce.png';
let resCache = new ResourcesCache(cacheName);
let imageRes = new ResourcesCache.AssetResource(imageUrl);
// cache the image
resCache.cache(imageRes)
.then(() => {
console.log('Image cached!');
});
// retrieve the image entry
resCache.fetch(imageRes)
// get a Resource instance for the image entry
.then(() => {
// get image data URI
return imageRes.raw();
})
.then((uri) => {
let img = new Image();
img.src = uri;
});
Cache an html page with external resources:
const cacheName = '__local';
const pageUrl = 'http://www.chialab.it/';
let resCache = new ResourcesCache(cacheName);
let htmlRes = new ResourcesCache.HTMLResource(pageUrl);
// cache the page
resCache.cacheRecursively(htmlRes)
.then(() => {
console.log('Page cached with assets!');
});
// retrieve the page entry
resCache.fetchRecursively(htmlRes)
// get a Resource instance for the page entry
.then(() => {
// get the page content
// with resources resolved as data URI
return htmlRes.raw();
})
.then((body) => {
//
});
Mime type sniffing is enabled by default, so you can use this short mode:
const cacheName = '__local';
const pageUrl = 'http://www.chialab.it/';
let resCache = new ResourcesCache(cacheName);
// cache the page
resCache.cacheRecursively(pageUrl)
.then(() => {
console.log('Page cached with assets!');
});