Kick starting with Progressive Web Apps Part 3

Kick starting with Progressive Web Apps Part 3

So far you have seen the resources get into the cache. But how do you get it out so that on a slow network or even no network you are still able to get the resources required to run our app. For this you need to intercept all the network requests by handling the fetch event in the service worker.

//service-worker.js
self.addEventListener('fetch',function(e){
    console.log("[Service Worker] Fetching REQUEST URL",e.  request.url);
   
    e.respondWith(
    caches.match(e.request).then(function(resp) {
        console.log("Response from Cache",resp)
        return resp || fetch(e.request)
    })
    .catch(function() {
      return console.log("Error Fallback");
    })
  );
})
caches.match evaluates the request and triggers the fetch and checks to see if it’s available in the cache.It then either responds with the cached version or uses fetch to get from the network.The response is then passed back to the page with e.respondWith.
You can also clone our network response and put in cache. So next in future if any requests comes, the cache response can be shown on the page quickly.
Note: Request method ‘POST’ is unsupported in service worker. Thus, POST requests cannot be cached in Cache Storage via service worker.
//service-worker.js
self.addEventListener('fetch',function(e){
    console.log("[Service Worker] Fetching REQUEST URL",e. request.url);
    e.respondWith(
    caches.match(e.request).then(function(resp) {
        console.log("Response from Cache",resp)
        return resp || fetch(e.request)
        .then(function(response) {
            return caches.open(cacheName).then(function(cache) 
            {
             cache.put(e.request,response.clone());
             return response;
            });  
       });
    })
    .catch(function() {
      return console.log("Error Fallback");
    })
  );
})

Your app should now cache its resources on the first load and then for subsequent loads return all resources from the cache. Thus, it can work even offline now!

Service Worker are extremely flexible and let’s you decide how you are going to cache your resources.

Have a look at some of the caching strategies.

  • Cache First , then Network : A request matches with the cache entry respond with that. Otherwise try to fetch the resource from the network.
  • Network First,then cache : Tries to handle request by fetching from the network. If the network request fails or times out it will try to fulfill from cache.
  • Cache Only : Tries to resolve the request from the cache.If the resource isn’t cached it fails.
  • Cache and Network race : Request the resource from cache and network in parallel. Then it responds with whichever responds first.
  • Cache Then Network : Two parallel requests are made one to the cache and one to the network.The idea is to show the cached data first and then update the cache and the page when network data arrives.

These are handful of caching strategies and choosing the right one depends on what type of caching your application needs!

To kick start with Progressive Web App you can go through my blogs :

1) Register service worker and cache the resources in our app on the initial load.

2) Update the old service worker and cache the new response in Cache Storage.

3) Get out the resources from the cache and intercept the network requests.

4) Make our web app installable via the Web App Manifest File.

5) Grey out the things when offline.
. . .

SoluteLabs is a high-performance team of 25 focused on mobile and web design and development; we have produced top #10 chart topping applications on Android and iOS app stores, graphics that have gone viral and applications with Millions of downloads.

Have a product idea?

Talk to our experts to see how you can turn it
into an engaging, sustainable digital product.

SCHEDULE A DISCOVERY MEETING