简体   繁体   中英

How to fetch json data and update the app shell using service worker

I have registered, active and cached resources via service worker, now i would like to know how to fetch JSON data and update the app shell using service worker.

I have registered, active and cached resources via service worker, now i would like to know how to fetch JSON data and update the app shell using service worker.

 var CACHE_NAME = 'my-cache-v1'; var urlsToCache = [ '/common.css', '/common.js' ]; self.addEventListener('install', function (e) { console.log('[Service Worker] Install'); e.waitUntil( caches.open(CACHE_NAME).then(function (cache) { console.log('[Service Worker] Caching app shell'); return cache.addAll(urlsToCache); }).then(function(e){ return self.skipWaiting(); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } var fetchRequest = event.request.clone(); return fetch(fetchRequest).then( function(response) { // Check if we received a valid response if(!response || response.status !== 200 || response.type !== 'basic') { return response; } var responseToCache = response.clone(); caches.open(CACHE_NAME) .then(function(cache) { cache.put(event.request, responseToCache); }); return response; } ); }) ); }); self.addEventListener('activate', function(e) { console.log('[ServiceWorker] Activate'); e.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (key !== CACHE_NAME) { console.log('[ServiceWorker] Removing old cache', key); return caches.delete(key); } })); }) ); return self.clients.claim(); }); 

One example to emulate is https://github.com/GoogleChrome/sw-precache/tree/master/app-shell-demo

It integrates sw-precache in a build process to keep the App Shell resources (HTML, JS, CSS) up to date.

It uses runtime caching (via a dependency on sw-toolbox ) to keep JSON API responses cached, as well as images.

It's based on a slightly out of date version of React/react-router/react-redux, but the general principles should still apply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM