ApiaryActive
Try: pause · settings · learn · wipe
← Community / Reading Room
PO
pwa · 3 min read

pwa offline caching strategies

=====================================================

=====================================================

As a developer building Progressive Web Apps (PWAs), you're likely familiar with the importance of providing a seamless user experience, even in areas with spotty internet connectivity. In this article, we'll explore various offline caching strategies to help you keep your app running smoothly, even when the network is down.

The Problem

When users access your PWA on a slow or unreliable connection, they expect a responsive and functional app, even if it can't fetch new data in real-time. However, the browser's default behavior is to block any requests that fail due to lack of connectivity, leaving your app broken and unresponsive.

The Solution

To overcome this limitation, we'll delve into four key offline caching strategies: App Shell, Runtime Cache, Stale-While-Revalidate, and Background Sync.

1. App Shell Caching


The App Shell is the bare minimum required for your PWA to function, including the navigation menu, footer, and any other essential UI elements. By pre-caching the App Shell, you ensure that users can access a basic version of your app even when offline.

Here's an example using Service Worker and TypeScript:

// sw.js (Service Worker)
self.addEventListener('install', event => {
  const cacheName = 'app-shell-cache';
  caches.open(cacheName).then(cache => {
    cache.addAll([
      '/offline-index.html',
      '/styles.css',
      '/script.js'
    ]);
  });
});

In this example, we open a cache called app-shell-cache and add the necessary files for the App Shell.

2. Runtime Cache


The Runtime Cache is used to store resources that are fetched on demand by your app, such as images or fonts. By caching these resources, you can ensure they're available even when offline.

Here's an example using Service Worker and JavaScript:

// sw.js (Service Worker)
self.addEventListener('fetch', event => {
  const cacheName = 'runtime-cache';
  caches.open(cacheName).then(cache => {
    return fetch(event.request).then(response => {
      if (response.ok) {
        cache.put(event.request, response.clone());
      }
    });
  });
});

In this example, we open a cache called runtime-cache and store any fetched resources in it.

3. Stale-While-Revalidate


Stale-While-Revalidate is an optimization technique that allows your app to use cached data while simultaneously fetching new data from the network. This ensures that users have access to updated information even when offline.

Here's an example using Service Worker and JavaScript:

// sw.js (Service Worker)
self.addEventListener('fetch', event => {
  const cacheName = 'data-cache';
  caches.open(cacheName).then(cache => {
    return fetch(event.request).then(response => {
      if (response.ok) {
        cache.put(event.request, response.clone());
      }
      return cache.match(event.request);
    });
  });
});

In this example, we open a cache called data-cache and store any fetched data in it. We also check the cache for an existing match before making a new request.

4. Background Sync


Background Sync is a feature that allows your app to sync with the server even when offline. This ensures that users can access updated information as soon as they come back online.

Here's an example using Service Worker and JavaScript:

// sw.js (Service Worker)
self.addEventListener('sync', event => {
  if (event.tag === 'background-sync') {
    fetch('/sync-data').then(response => {
      // Handle response data here...
    });
  }
});

In this example, we listen for a sync event with the tag background-sync and make a request to sync any pending data.

When NOT to Use It

While these offline caching strategies can significantly improve your app's user experience, there are cases where they might not be suitable:

  • High-velocity updates: If your app requires real-time updates or has very short-lived content (e.g., live scores or stock prices), you may want to prioritize online-only functionality.
  • Small payloads: For apps with extremely small data payloads, the overhead of caching and syncing might outweigh the benefits.

Related Apiary Lessons

Conclusion

PWA offline caching strategies are a crucial aspect of building robust and user-friendly apps. By implementing App Shell, Runtime Cache, Stale-While-Revalidate, and Background Sync techniques, you can ensure your app remains functional even in areas with limited connectivity.

As the great beekeeper once said: "A PWA without offline caching is like a hive without honey – it's just not worth building!"

Frequently asked
What is pwa offline caching strategies about?
=====================================================
What should you know about the Problem?
When users access your PWA on a slow or unreliable connection, they expect a responsive and functional app, even if it can't fetch new data in real-time. However, the browser's default behavior is to block any requests that fail due to lack of connectivity, leaving your app broken and unresponsive.
What should you know about the Solution?
To overcome this limitation, we'll delve into four key offline caching strategies: App Shell, Runtime Cache, Stale-While-Revalidate, and Background Sync.
What should you know about 1. App Shell Caching?
The App Shell is the bare minimum required for your PWA to function, including the navigation menu, footer, and any other essential UI elements. By pre-caching the App Shell, you ensure that users can access a basic version of your app even when offline.
What should you know about 2. Runtime Cache?
The Runtime Cache is used to store resources that are fetched on demand by your app, such as images or fonts. By caching these resources, you can ensure they're available even when offline.
References & sources
  1. Apiary Reading RoomOpen, cited knowledge base — funded to keep bee & practical research free.
From the Apiary Reading Room. Opinion & editorial — not financial advice. We don't overclaim.
More from the Reading Room