官术网_书友最值得收藏!

Providing a stale version on error

If you travel a lot, chances are you have often experienced a lot of zero network connectivity. This is frustrating, especially if you want to view previously viewed pages. In this recipe, we will look at how we can address this issue by providing the user with the stale version from the cache.

Getting ready

To get started with service workers, you will need to have the service worker experiment feature turned on in your browser settings. If you have not done this yet, refer to the previous recipe: Setting up service workers. Service workers only run across HTTPS. To find out how to set up a development environment to support this feature, refer to the following recipes: Setting up GitHub pages for SSL, Setting up SSL for Windows, and Setting up SSL for Mac.

How to do it...

Follow these instructions to set up your file structure (or you can find the files in the provided directory, 01/05):

  1. First, we need to create an index.html file as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Stale on Error</title>
    </head>
    <body>
      <p>Registration status: <strong id="status"></strong></p>
      <script>
        if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register(
            'service-worker.js',
            { scope: './' }
          ).then( function(serviceWorker) {
            document.getElementById('status').innerHTML = 
            'successful';
          }).catch(function(error) {
            document.getElementById('status').innerHTML = error;
          });
    
        } else {
            document.getElementById('status').innerHTML = 
            'unavailable';
          }
      </script>
    </body>
    </html>
  2. Create a JavaScript file called service-worker.js in the same folder as the index.html file with the following code:
    var version = 1;
    var cacheName = 'stale- ' + version;
    
    self.addEventListener('install', function(event) {
        self.skipWaiting();
    });
    
    self.addEventListener('activate', function(event) {
        if (self.clients && clients.claim) {
            clients.claim();
        }
    });
    
    self.addEventListener('fetch', function(event) {
      
        event.respondWith(
            fetch(event.request).then(function(response) {
                caches.open(cacheName).then(function(cache) {
                    
                    if(response.status >= 500) {
                        cache.match(event.request).
                                            then(function(response) {
                            
                            return response;
                        }).catch(function() {
                         
                            return response;
                        });
                    } else {
                          cache.put(event.request, response.clone());
                        return response;
                    }
                });
            })
        );
    });
  3. With your two files in place, navigate to index.html.

How it works...

When the registration is successful, we inspect the state of the registration and print it to the browser.

In the service-worker.js file, we always fetch the response from the network:

event.respondWith(
        fetch(event.request).then(function(response) {

If we received an error response, we return the stale version from the cache:

if(response.status >= 500) {
                    cache.match(event.request).
                                        then(function(response) {
                        // Return stale version from cache
                        return response;
})

If we can't find the stale version, we return the network response, which is the error:

}).catch(function() {
                        
return response;
});

If the response was successful (response code 200), we update the cached version:

} else {
cache.put(event.request, response.clone());
   return response;
}

There's more...

The put() method of the cache interface allows key/value pairs to be added to the current cache object. The put() method also overrides any key/value pair previously stored in the cache that matches the request:

fetch(url).then(function (response) {
  return cache.put(url, response);
});
主站蜘蛛池模板: 隆回县| 启东市| 望江县| 洛扎县| 墨竹工卡县| 钟祥市| 浠水县| 颍上县| 平顶山市| 砀山县| 和静县| 古蔺县| 资中县| 青浦区| 五家渠市| 永川市| 永新县| 满洲里市| 曲水县| 霞浦县| 那曲县| 秦皇岛市| 子长县| 湘阴县| 泸西县| 延庆县| 灵山县| 永登县| 郯城县| 息烽县| 遵化市| 翁牛特旗| 浦城县| 汨罗市| 天长市| 北宁市| 芦溪县| 庆元县| 永修县| 牙克石市| 张家港市|