Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML/JS for testing Cache storage and Disk cache
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button onClick="clearCache()">Clear cache</button>
<button onClick="loadImages()">Load images</button>
<button onClick="cacheImages()">Cache images</button>
<div id="images"></div>
<script>
var imgUrls = [];
for(var i = 1; i <= 100; i++) {
imgUrls.push('img/' + i + '.png');
}
async function clearCache() {
var cache = await caches.open('test-bucket');
var keys = await cache.keys();
keys.forEach((key) => { cache.delete(key); });
}
async function cacheImages() {
var cache = await caches.open('test-bucket');
cache.addAll(imgUrls);
}
function loadImages() {
var container = document.querySelector('#images');
imgUrls.forEach((url) => {
var img = document.createElement('img');
img.src = url;
container.appendChild(img);
});
}
navigator.serviceWorker.register('./sw.js');
</script>
</body>
</html>
self.addEventListener('install', function(event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', function(event) {
var req = event.request;
event.respondWith(async function() {
var cache = await caches.open('test-bucket');
var resp = await cache.match(req);
if (resp) return resp;
console.info('Not found in cache', req.url);
return fetch(req);
}());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.