For simplicity, let's say a given web app is using some files that exist in the root directory like,
First set: image1.jpg
info1.txt
video1.mp4
and
Second set: image2.jpg
info2.txt
video2.mp4
as well as
Third set: image3.jpg
info3.txt
video3.mp4
In this case «due to priority reasons» we would like these to be cached set by set in order. That means, the caching of the second group of files will start only after the first set is «hopefully» done caching, then third will start after second is finished etc.
Once we are good to go with,
if ('caches' in window){
// Safe to try
}
we want to use
const myCache1 = await caches.open('my-cache-1');
const myCache2 = await caches.open('my-cache-2');
const myCache3 = await caches.open('my-cache-3');
to create the cache containers (like folders hidden inside the browser),
and then we can
const firstGroup = ['/image1.jpg', '/info1.txt', '/video1.mp4'];
const secondGroup = ['/image2.jpg', '/info2.txt', '/video2.mp4'];
const thirdGroup = ['/image3.jpg', '/info3.txt', '/video3.mp4'];
but now we want to chain myCache1.addAll(firstGroup);
myCache2.addAll(secondGroup);
myCache3.addAll(thirdGroup);
so that files get downloaded depending on their importance (or whatever logical reason to put things in order).
Note1: The .then().catch().finally()
chaining is essential but async/await
answers are also welcome.
Note2: Inclusion of error handling in case of flaky internet connection would be nice but not a must.
It seems like all you need to do is call the addAll
s in order with async/await, like so:
async function loadFiles () {
const myCache1 = await caches.open('my-cache-1');
const myCache2 = await caches.open('my-cache-2');
const myCache3 = await caches.open('my-cache-3');
const firstGroup = ['/image1.jpg', '/info1.txt', '/video1.mp4'];
const secondGroup = ['/image2.jpg', '/info2.txt', '/video2.mp4'];
const thirdGroup = ['/image3.jpg', '/info3.txt', '/video3.mp4'];
try {
// load group 1 first
await myCache1.addAll(firstGroup);
// then load group 2
await myCache2.addAll(secondGroup);
// then load group 3
await myCache3.addAll(thirdGroup);
} catch(err) {
// error handling goes here
console.error(err);
}
}
loadFiles();