Based on Abdelrahman Omran PWA presentation, and Google PWA Codelab
Step 2. Use service workers to pre-cache the App Shell
Step 4. Support native integration & Deploy online
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';
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);
})
);
}
});
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.