Skip to main content
All CollectionsAll Things Caching
How to precache resources to make them available offline
How to precache resources to make them available offline

Learn how to do this with your own custom code and with Progressier

Kevin Basset avatar
Written by Kevin Basset
Updated over a year ago

What's precaching?

Precaching allows you to preload resources before they're actually needed in your app so that they're available very quickly when they're eventually needed.

Precaching happens during the installation process of your service worker. You instruct the service worker to fetch a list of URLs and then add them to the cache. With the right strategy, these resources can then be retrieved from the cache directly later on.

Precaching using your own custom code

If you're handling this yourself, here is a simplistic example of code to add to your service worker to precache a set of URLs.

self.addEventListener('install', function(event){
let urlsToPrecache = [
"https://example.com/homepage",
"https://example.com/user-avatar.jpg",
"https://anotherdomain.com/style.css"
];

event.waitUntil(caches.open('cache-name').then(function(cache) {
return cache.addAll(urlsToPrecache);
}));
});

There are a number of problems with the standard custom code approach, though. As your app evolves, you'll have to modify your hard-coded list of urlsToPrecache. You'll have to remember to do so and redeploy your app. This can get annoying pretty quickly.

It's also easy to make mistakes. You might want to precache resources from other domains. With CORS restrictions, however, it's easy to try precaching a resource that can't actually be precached, e.g. if it contains a cache-control: no-store header or if it does NOT contain a access-control-allow-origin: * header. These issues can be pretty tough to debug.

Precaching using Progressier

I built Progressier in part to make it easy to implement precaching in your own app while automatically shielding you from common mistakes. In a nutshell, this is how it works:

  1. Start by making a scan of your app. Add a page URL (and optionally authentication headers to send with the request), and Progressier will visit the page and retrieve a list of all the resources that the page requests while loading (until about 10 seconds after load).

  2. Now, open one of the strategies. You'll see the resources that this strategy applies to. Simply click on the toggle in the Precache column, and you're done!

A nice benefit of using Progressier for precaching is that we tell you which of the resources can actually be precached โ€” automatically protecting you from lots of potential mistakes.

Did this answer your question?