Skip to content

PWA Weather: Offline Is a Feature

A small weather app built as a Progressive Web App shows why offline behavior is a product decision and how honestly a UI should deal with outdated data.

≈ 11 min readSoftwareArchitecture

PWA Weather: Offline Is a Feature

On the subway between two stations, no signal. The weather app opens, briefly shows a loading spinner and then: nothing. A white screen. And yet this morning’s weather would have been perfectly fine – the question was whether to take the umbrella, not whether it’s 21.3 or 21.4 degrees this minute. The app had even loaded this data before. It just threw it away, because nobody decided that it’s worth anything without a network.

This white screen is not a technical defect. It is the result of a non-decision. Somewhere in the backlog, “offline support” was probably listed as a technical nice-to-have, behind the next feature and the redesign after that. That is exactly what I consider the mistake in thinking: offline is not an add-on you bolt onto a finished app later. Offline is a feature with product questions – what should work without a network, what explicitly should not, and how honestly the UI shows the state of the data.

A small demo as a test bench#

To play this through for myself, I created a small repository in April of this year: pwa-weather-demo. It is deliberately not a product but a rebuild exercise following Google’s tutorial “Your First Progressive Web App” – one weather card per city, a public weather API behind it, a service worker in front. Locally, the whole thing starts with a simple http-server; it needs no more infrastructure than that. The value isn’t in the feature set but in the fact that a manageable example lets you touch every decision one at a time.

And there are more decisions than the word “caching” suggests. While working through it, I noticed that the real work isn’t in the service worker code. You can write that in an afternoon. The work lies in the question of what answer the app owes a person without a network connection.

Offline is a product question, not a cache option#

For the weather app, my answer looks like this:

  • The most recently loaded weather for the saved cities is shown – always, immediately, even without a network.
  • The UI itself (layout, icons, fonts, logic) loads completely from the local cache.
  • Searching for new places doesn’t work offline – and says so, instead of letting a spinner turn.
  • Every weather card shown carries a timestamp: “Updated 2 hours ago” instead of silently old data.

The third point matters to me. It would be technically possible to cache search results too and show something offline. But a place search against a two-day-old cache doesn’t deliver a search; it delivers a dummy. Not everything that can be cached should be cached. The line runs along the question of whether an outdated answer is still an honest answer: this morning’s weather is honest, clearly dated information. A search result from the day before yesterday is not.

The fourth point is the second half of the same decision. If you show old data without marking it as old, your interface is lying. A small timestamp turns the same record from potential misinformation into useful information. It costs one line of UI and a date – and it’s the difference between “the app shows something” and “the app tells me what it knows and how sure it is.”

The service worker: a proxy with a lifecycle#

Technically, all of this hinges on the service worker – a script that the browser runs separately from the page and that sits as a programmable proxy between the app and the network. Every request from the page goes through its fetch handler, and there, code instead of chance decides whether a response comes from the network, from the cache or from a combination of both.

If you work with it for the first time, you stumble less over the API than over the lifecycle. A service worker is registered, installed, waits if necessary for the old version to end and only then takes control of the page:

flowchart LR
  A[register] --> B[install<br/>precache the app shell]
  B --> C[waiting<br/>old version still running]
  C --> D[activate<br/>clean up old caches]
  D --> E[fetch<br/>control requests]

The registration itself is unspectacular and belongs at the end of the app startup:

// app.js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('/service-worker.js')
    .then(function (registration) {
      console.log('service worker registered, scope:', registration.scope);
    })
    .catch(function (error) {
      console.error('service worker registration failed', error);
    });
}

The if is not a formality but part of the architecture: in browsers without service workers, the app simply keeps running as a normal website. More on that later, because in 2017 this case is anything but exotic.

Two quirks of the lifecycle actually cost me time in the demo. First: by default, an updated service worker only takes over once all tabs of the old version are closed – if you just reload during development and wonder why the new code doesn’t apply, you’re fighting waiting, not a bug. Second: the activate step is the right place to delete old cache versions. If you skip it, you accumulate another cache with every deployment and wonder months later about the storage usage.

App shell: the frame always comes from the cache#

The first cache decision concerns the app shell – everything the application needs for display before even a single byte of weather data is there: HTML, CSS, JavaScript, icons. These files only change with a deployment, so they are put into the cache completely once during install (precache) and always served from there afterward:

// service-worker.js
var SHELL_CACHE = 'weather-shell-v1';
var DATA_CACHE = 'weather-data-v1';

var SHELL_FILES = [
  '/',
  '/index.html',
  '/styles/app.css',
  '/scripts/app.js',
  '/images/icons/icon-192.png'
];

self.addEventListener('install', function (event) {
  event.waitUntil(
    caches.open(SHELL_CACHE).then(function (cache) {
      return cache.addAll(SHELL_FILES);
    })
  );
});

self.addEventListener('activate', function (event) {
  event.waitUntil(
    caches.keys().then(function (keys) {
      return Promise.all(
        keys
          .filter(function (key) {
            return key !== SHELL_CACHE && key !== DATA_CACHE;
          })
          .map(function (key) {
            return caches.delete(key);
          })
      );
    })
  );
});

The version number in the cache name is the deployment concept in its simplest form: new shell, new name, old caches get thrown out on activate. Tools like sw-precache generate this part from the build, and Workbox has just been released as a fresh successor that brings the common strategies as a library. For the demo, I deliberately wrote it by hand – not out of principle, but because you should only leave a strategy to a generator with a clear conscience once you’ve formulated it yourself.

Two kinds of data, two strategies#

The more interesting decision happens in the fetch handler, because the app shell and the weather data need opposite strategies. The shell should arrive as fast as possible and may well be one deployment cycle old: cache first. The weather data should be as fresh as possible, and the cache is just the safety net for the subway moment: network first, with the last known response as a fallback.

flowchart TD
  R[fetch event] --> Q{Path starts with<br/>/api/weather?}
  Q -- yes --> N[Network first]
  N -- response ok --> C1[Copy into weather-data-v1<br/>response to the app]
  N -- no network --> C2[last known response<br/>from the cache]
  Q -- no --> S[Cache first:<br/>app shell]
  S -- hit --> C3[serve immediately]
  S -- no hit --> C4[pass through to the network]

In code, this switch looks like this:

self.addEventListener('fetch', function (event) {
  var url = new URL(event.request.url);

  if (url.pathname.indexOf('/api/weather') === 0) {
    // network first, cached data as offline fallback
    event.respondWith(
      fetch(event.request)
        .then(function (response) {
          var copy = response.clone();
          caches.open(DATA_CACHE).then(function (cache) {
            cache.put(event.request, copy);
          });
          return response;
        })
        .catch(function () {
          return caches.match(event.request);
        })
    );
    return;
  }

  // app shell: cache first, network as fallback
  event.respondWith(
    caches.match(event.request).then(function (cached) {
      return cached || fetch(event.request);
    })
  );
});

An alternative for the data route would be stale-while-revalidate: deliver the cached response immediately and fetch the fresh one in the background in parallel, which is then ready for the next render. For a weather app, that’s a legitimate choice – the display appears instantly, and the update trickles in afterward. In the demo, I still chose network-first, because with weather data the fresh response deserves priority as long as the network is there. The point is not which of the two strategies is “right.” The point is that it’s a choice with visible consequences – and that it’s made per route, not across the board for the whole app. Jake Archibald’s Offline Cookbook spells out these patterns one by one and has been my reference for them for years.

The age of the data belongs in the UI#

So that “showing old data” doesn’t turn into quietly slipping it in, the app has to know how old a response is. Conveniently, this information is already in the cached response – the Date header of the original server response is stored with it:

// show data age when rendering a cached response
caches.match('/api/weather?city=berlin').then(function (cached) {
  if (!cached) {
    return;
  }
  var fetchedAt = new Date(cached.headers.get('date'));
  var ageInMinutes = Math.round((Date.now() - fetchedAt.getTime()) / 60000);
  showLastUpdated(ageInMinutes); // "Stand: vor 120 Minuten"
});

That’s ten lines, and they change the character of the app. “Why is it showing me sunshine when it’s raining outside” becomes “ah, that’s the state from this morning.” In a project review, I would weigh these ten lines higher than the entire cache logic underneath – the cache logic decides whether something is shown; these lines decide whether you can trust what’s shown.

Manifest, HTTPS and the home screen#

Besides the service worker, two more building blocks belong to a PWA. The web app manifest describes how the app behaves when it lands on the home screen:

{
  "name": "PWA Weather",
  "short_name": "Weather",
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#3f51b5",
  "theme_color": "#3f51b5",
  "icons": [
    {
      "src": "images/icons/icon-192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}

With a manifest plus a registered service worker plus repeated use, Chrome on Android offers “Add to Home screen” on its own – the app then starts without browser chrome, with its own icon, and feels surprisingly like an installed application. Lighthouse checks whether a page meets the criteria; the PWA audit reliably complains about missing icons, missing offline behavior of the start route or missing HTTPS.

HTTPS is not a recommendation here but a requirement: browsers only register service workers over secure connections (with localhost as the development exception). And that’s a good thing – you don’t want to deliver a script that may intercept and answer every request of a domain over a connection that can be tampered with.

The honest limit: Safari#

Now the part that comes up suspiciously quietly in many PWA articles this year: Safari has no service worker. Neither on the Mac nor – and this weighs more – on iOS. Chrome, Firefox and Opera support the API, Microsoft Edge is working on it, and on the WebKit status board the entry has at least recently moved to “In Development.” But as of today, August 2017, a PWA on an iPhone is simply a normal website: no offline cache, no intercepting of requests, no install banner.

That’s no reason to give up on it – but it absolutely belongs in the product decision, not in a footnote. For the weather demo, this concretely means: the app has to work fully without a service worker, just without the offline comfort. The service worker is an enhancement layer (Progressive Enhancement in the original sense of the term), not a prerequisite. If you build your app so that it breaks without a service worker, you have nothing at all on iOS. If you build it so that the service worker adds behavior instead of carrying it, you have a decent website on iOS and an app on Android that survives the subway moment.

Depending on the target audience, this shifts the calculation considerably. With an audience with a high iOS share, the PWA effort today mainly buys you better load times through the shell cache in Chrome and Firefox – not nothing, but a different promise than “works offline.” This calculation should be openly on the table in the team before anyone writes “offline-capable” on a slide.

Bottom line#

The technology behind the demo is manageable: a lifecycle, two cache strategies, a manifest, HTTPS. What sticks is something else. The white screen on the subway doesn’t happen because caching is hard – it happens because “offline” was never treated as a feature, with the same questions as any other feature: What exactly should it be able to do? What deliberately not? How does the person in front of it recognize what’s happening right now?

My answers for the weather app – last known weather yes, place search no, timestamp always – are not universal. A banking app draws the line differently, a news site differently again. The only universal thing is that this line has to be drawn before the first fetch handler is written. The service worker carries out a product decision. It doesn’t replace it.

Further reading#

Revised and translated from German with the help of AI.