Skip to content

Instantly share code, notes, and snippets.

@Omranic
Last active January 31, 2024 18:30
Show Gist options
  • Save Omranic/1b97059b1527e1878fdc5c51ada3e057 to your computer and use it in GitHub Desktop.
Save Omranic/1b97059b1527e1878fdc5c51ada3e057 to your computer and use it in GitHub Desktop.
3. Use service workers to cache the forecast data - Your First Progressive Web App

Your First Progressive Web App

Based on Abdelrahman Omran PWA presentation, and Google PWA Codelab


Step 1. Fast first load

Step 2. Use service workers to pre-cache the App Shell

Step 3. Use service workers to cache the forecast data

Step 4. Support native integration & Deploy online


Cache Wethear Data

Open service-worker.js and search for the following line:

var shellCacheName = 'pwa-weather-shell-v1';

Add the following code below the previous line:

var dataCacheName = 'pwa-weather-data-v1';

Update Data Cache

In the same file service-worker.js search for the following code:

if (key !== shellCacheName) {

Add replace it with the following code:

if (key !== shellCacheName && key !== dataCacheName) {

Still in the same file service-worker.js search for the following code:

// Listen to fetching event
self.addEventListener('fetch', function(e) {
  console.log('[ServiceWorker] Fetch', e.request.url);
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});

And replace it with the following code:

// Listen to fetching event
self.addEventListener('fetch', function(e) {
  console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = 'https://query.yahooapis.com/v1/public/yql';

  // Check if this is data or app shell request
  if (e.request.url.indexOf(dataUrl) > -1) {
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

Serve Data Offline From Cache

Open scripts/app.js and search for the following line:

    // TODO add cache logic here

Add the following code below the previous line:

    // Check if browser supports local cache
    if ('caches' in window) {
      // Get cached weather data if exists
      caches.match(url).then(function(response) {
        if (response) {
          response.json().then(function updateFromCache(json) {
            var results = json.query.results;
            results.key = key;
            results.label = label;
            results.created = json.query.created;
            app.updateForecastCard(results);
          });
        }
      });
    }

Note: now your weather app fully supports offline browsing, you can go offline & try it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment