Skip to content

Instantly share code, notes, and snippets.

@dnesteryuk
Created May 28, 2019 19:27
Show Gist options
  • Save dnesteryuk/eff23819e44ec61c842a16d0237b8c96 to your computer and use it in GitHub Desktop.
Save dnesteryuk/eff23819e44ec61c842a16d0237b8c96 to your computer and use it in GitHub Desktop.
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