PWA (Progressive Web Apps)

A Progressive Web App uses modern web capabilities to deliver an app-like user experience. if apache is down it can display static contents.
Key Points:
Reliable: Fast loading and works offline.
Fast: Smooth Animations, jank-free scrolling and seamless navigation even on flaky networks.
Engaging: Launched from home screen and can receive a push notification.
Paste below scripts inside home page
<script type="text/javascript">
      if (navigator.serviceWorker.controller) {
   console.log('[PWA Builder] active service worker found, no need to register')
 } else {
   //Register the ServiceWorker
   navigator.serviceWorker.register('pwabuilder-sw.js', {
     scope: './'
   }).then(function(reg) {
     console.log('Service worker has been registered for scope:'+ reg.scope);
   });
 }
 </script>
And create one js file on root name as pwabuilder-sw.js.
Service Workers
Service Workers are an incredibly powerful technology behind a Progressive Web App. They power offline functionality, push notifications, background content updating, content caching etc.

//Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener('install', function(event) {
  var indexPage = new Request('index.html');
  event.waitUntil(
    fetch(indexPage).then(function(response) {
      return caches.open('pwabuilder-offline').then(function(cache) {
        console.log('[PWA Builder] Cached index page during Install'+ response.url);
        return cache.put(indexPage, response);
      });
  }));
});

//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
  var updateCache = function(request){
    return caches.open('pwabuilder-offline').then(function (cache) {
      return fetch(request).then(function (response) {
        console.log('[PWA Builder] add page to offline'+response.url)
        return cache.put(request, response);
      });
    });
  };

  event.waitUntil(updateCache(event.request));

  event.respondWith(
    fetch(event.request).catch(function(error) {
      console.log( '[PWA Builder] Network request Failed. Serving content from cache: ' + error );

      //Check to see if you have it in the cache
      //Return response
      //If not in the cache, then return error page
      return caches.open('pwabuilder-offline').then(function (cache) {
        return cache.match(event.request).then(function (matching) {
          var report =  !matching || matching.status == 404?Promise.reject('no-match'): matching;
          return report
        });
      });
    })
  );
})

Testing: Open you Html page in the browser. Now Down apache server with the command
sudo service apache2 stop
Now you can view your page on the browser.

Source URL : https://www.pwabuilder.com/serviceworker

Comments

Post a Comment