Latest news

[Ultimate Guide] Converting Your Site To Google Progressive Web Apps (Part 1)

No comments

What are Google Progressive Web Apps?

Google Progressive Web Apps  incorporate a combination of the best of native apps and the best of webs to deliver the greatest experience to users. These are fast, engaging and reliable.

Owing to the Google Progressive Web Apps, it’s easy to earn a place on the customers’ homescreen. More and more businesses are testing and applying this new technology and getting significant results, for instance: Alibaba, AliExpress, Flipkart, Lancome, etc.

In October, Tigren has released the Free Google Progressive Web Apps Extension for Magento 2. If you are running a Magento store, there is no reason for not installing this awesome extension.

However, if you want to build your own Google Progressive Web Apps, we will give you a detailed instruction. Also, if you have any problems when following our guide, be free to ask, we’re glad to help. Now, let’s get started!

First and foremost, you must use HTTPS sites or URL like http://127.0.0.1/yourdomain.

1. Service Worker

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. They include features like push notifications and background sync.

  • Register a Service Worker

To install a service worker, you need to register it first in your page in order to tell the browser where your service worker JavaScript file lives.

<?php
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/serviceWorker.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed 🙁
      console.log('ServiceWorker registration failed: ', err);
    });
  )};
)
?>

This code checks to see whether the service worker API is available or not, and if it is, the service worker at /serviceWorker.js is registered once the page is loaded.

One subtlety with the register() method is the location of the service worker file. If you want to control all pages of your website, you should put Service Worker at the root folder. This means that the service worker’s scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. Otherwise, if we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

Now you can check that a service worker is enabled by going to chrome://inspect/#service-workers and looking for your website.

  • Install a Service Worker

Let’s move to the point of view of the service worker script, which handles the install event.

For the most basic example, you need to define a callback for the install event and decide which files you want to cache.

self.addEventListener('install', function(event) {
  // Perform install steps
});

Inside of our install callback, we need to take the following steps:

1. Open a cache.
2. Cache our files.
3. Confirm whether all the required assets are cached or not.

var CACHE_NAME = 'pwa-tigren-cache-v1';
var urlsToCache = [
  '/',
  '/styles/main.css',
  '/script/main.js'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

If you don’t have any static file need to cache you can use this code:

var CACHE_NAME = 'pwa-tigren-cache-v1';
self.addEventListener('install', function (event) {
    // Perform install steps
    event.waitUntil(
        self.skipWaiting()
    );
});
  • Cache and return requests

After the service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events, for example:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

Here we’ve defined our fetch event and within event.respondWith(), we pass in a promise from caches.match(). This method looks at the request and finds any cached results from any of the caches your service worker created.

If we have a matching response, we return the cached value, otherwise we return the result of a call to fetch, which will make a network request and return the data if anything can be retrieved from the network.

If we want to cache new requests cumulatively, we can do so by handling the response of the fetch request and then adding it to the cache like below.

self.addEventListener('fetch', function (event) {
    if (event.request.method !== 'POST' && event.request.url.toString() &&
        event.request.url.toString().indexOf('/admin/') === -1 &&
        event.request.url.toString().indexOf('/checkout/') === -1 &&
        event.request.url.toString().indexOf('/cart/') === -1 &&
        event.request.url.toString().indexOf('/key/') === -1 &&
        event.request.url.toString().indexOf('/adminhtml/') === -1) {
        event.respondWith(
            caches.match(event.request)
                .then(function (response) {
                    // Cache hit - return response
                    if (response) {
                        return response;
                    }

                    // IMPORTANT: Clone the request. A request is a stream and
                    // can only be consumed once. Since we are consuming this
                    // once by cache and once by the browser for fetch, we need
                    // to clone the 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;
                            }

                            // IMPORTANT: Clone the response. A response is a stream
                            // and because we want the browser to consume the response
                            // as well as the cache consuming the response, we need
                            // to clone it so we have two streams.

                            var responseToCache = response.clone();
                            caches.open(CACHE_NAME)
                                .then(function (cache) {
                                    cache.put(event.request, responseToCache);

                                });

                            return response;
                        }
                    );
                })
        );
    }
});
  • Update a Service Worker

After a certain period of time, your service worker will need updating. When that time comes, let’s follow these steps:

1. Update your service worker JavaScript file. When the user navigates to your site, the browser tries to redownload the script file that defined the service worker in the background. If there is even a byte’s difference in the service worker file compared to what it currently has, it considers it new.
2. Your new service worker will be started and the install event will be fired.
3. At this point the old service worker is still controlling the current pages so the new service worker will enter a waiting state.
4. When the currently open pages of your site are closed, the old service worker will be killed and the new service worker will take control.
5. Once your new service worker takes control, its activate event will be fired.

The following code would do this by looping through all of the caches in the service worker and deleting any caches.

<?php
self.addEventListener('activate', function (event) {
    console.log('[ServiceWorker] Activate');
    event.waitUntil(
        caches.keys().then(function (cacheNames) {
            return Promise.all(
                cacheNames.map(function (cacheName) {
                    return caches.delete(cacheName);

                })
            );
        })
    );
    return self.clients.claim()
});
?>

NOTES: If you don’t have a clear caching strategy, it will have negative impact on both your development cycle and your users.

Now, your website will be able to run offline. You can check your service worker by using Devtools. Open the DevTools Application panel and select Service Wokers.

turn normal website to google progressive web apps

 

This is the end of the first part in the Converting Your Website to Google Progressive Web Apps Guideline. In the next blog post, we will continue with the Web App Install Banners and learn how to add your web google progressive web apps to the homescreen. See you!

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

April Lee[Ultimate Guide] Converting Your Site To Google Progressive Web Apps (Part 1)

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *