How to develop a progressive web application PWA

Time:2022-1-5
catalogue
  • summary
  • requirement
  • App URL
  • What are the technical components required for PWA?
    • Manifest file
    • What is a service worker?
    • Background transmission
  • summary

    summary

    Since Apple launched the iPhone app store, apps have become an indispensable part of our lives, as well as for physical businesses. Now all industries are launching their own apps, but has anyone thought of such a scenario, If your potential customers haven’t installed your app, or even if they do, they uninstall your app because the customer’s mobile phone storage space is tight? Is there any technology to make the app lighter and easier to install? The answer is “yes”.

    Progressive web application is born for this purpose. It has the characteristics of both web application functions and functions previously only available in native applications. Progressive web application can be started from the icon on the main screen or according to the push notification. The loading time is almost negligible, and it can be packaged for offline use in addition to online use.

    Most importantly, the way progressive web applications are created on your mobile phone is also very simple, because they are only an enhancement to your website. When someone visits your website for the first time, the function of PWA will be automatically created on your mobile phone after you authorize it.

    Next, we’ll take a look at how to create our own PWA application.

    requirement

    To begin this tutorial, you must install the following software:

      Node version 8.9 and above (HTTPS: / / nodejs. Org / en / download /) Yarn( https://yarnpkg.com ) Git.

    As the initial project of this tutorial, you can clone the following GitHub libraries:

    git clone https://github.com/petereijgermans11/progressive-web-app

    Then, go to the following directory

    cd pwa-article / pwa-app-manifest-init

    Install the dependencies and start the project with the following command

    npm i && npm start

    Open the app at http: / / localhost: 8080

    App URL

    There are many ways to access my local host: to remotely access the address of port 8080 published on your machine. To do this, you can use ngrok. See: https://ngrok.com/

    Install ngrok using the following command:

    npm install -g ngrok

    Run the following command in the terminal. This command generates aExternally accessibleURL

    ngrok http 8080

    Then in ChromeMobile deviceBrowse to the generated web address.

    What are the technical components required for PWA?

    PWA has three important technical components to coordinate work, including:

    Manifest file, service worker and run under HTTPS.

    Manifest file

    The manifest file is a JSON configuration file, which contains the basic information of PWA, such as application icon, web application name and background color. If the browser detects that there is a PWA manifest file in the website, chrome will automatically display the “add to home screen” button. If the user clicks agree, the icon will be added to the main screen and PWA will be installed.

    Create a manifest json

    PWA’s manifest The JSON file is as follows:

    JSON format

    
    {
      "name": "Progressive Selfies",
      "short_name": "PWA Selfies",
      "icons": [
        {
          "src": "/src/images/icons/app-icon-192x192.png",
          "type": "image/png",
          "sizes": "192x192"
        },
        {
          "src": "/src/images/icons/app-icon-512x512.png",
          "type": "image/png",
          "sizes": "512x512"
        }
      ],
      "start_url": "/index.html",
      "scope": ".",
      "display": "standalone",
      "background_color": "#fff",
      "theme_color": "#3f51b5"
    }

    Tell the browser the list of your apps

    With index Create manifest. HTML file in the same level directory JSON file. After the manifest file is created, add the manifest file reference link to index HTML.

    
    <link rel=”manifest” href=”/manifest.json”>

    Introduction to manifest attribute

    Manifest has many configuration properties. Next, we will briefly introduce the properties

    • name、short_ Name: Specifies the name of the web application, short_ Name is the abbreviation of the application. When there is not enough space to display the name attribute of the application, the system will use short_ name 。
    • Display: the display attribute specifies the display mode of the web application. It has four values to configure: fullscreen, standalone, minimal UI and browser, but the commonly used attributes are fullscreen and standalone. Fullscreen: full screen standard: the application opened in this mode will not appear in the browser’s address bar, so it looks more like a native application. Minimal UI and browser: are not different from accessing with the browser.
    • Orientation: control the display direction of the web application and prohibit the mobile phone from turning the screen.
    • icons、background_ Color: icon is used to specify the application icon, background_ Color is the background color before the application is loaded. By setting these two properties, the splash screen of the application can be combined.
    • theme_ Color: defines the default theme color for the application.
    • Description: set a description of the application.

    The above are some descriptions of the attributes of PWA manifest file. We set the completed manifest file and place it in the interface with index HTML file can be added to the directory at the same level.

    Open the chrome developer tool – Application – manifest to check whether the added manifest file has been loaded. If there is no information in the figure below, we can reload it by restarting the server NPM start.

    What is a service worker?

    Service worker (SW) is a piece of JavaScript that acts as a proxy between the browser and the web server. Service worker can realize common functions of native applications such as offline caching, message push, silent update and so on in browser based web applications, so as to provide better and richer use experience for web applications.

    In addition, this API also allows the use of caching to support offline experience, so that developers can fully control the user experience

    Service worker lifecycle

    For service worker, the basic setting steps are as follows:

    • First, you should register SW. If SW is registered, the browser will automatically start the installation according to the installation event.
    • After installing SW, it will receive an activation event. This activation event can be used to clean up resources used in previous versions of SW.

    The actual operation should first create a and index HTML peer, named SW JS. Then index HTML file, add a base tag as follows:

    
    <base href="/" rel="external nofollow" >

    Finally, in Src / JS / APP JS add the following code to register SW. This code will be activated during page “loading”.

    You can open chrome devtools – application – service worker to check whether SW is enabled.

    
    window.addEventListener('load', () => {
        const base = document.querySelector('base');
        let baseUrl = base && base.href || '';
        if (!baseUrl.endsWith('/')) {
            baseUrl = `${baseUrl}/`;
        } 
       
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register(`${baseUrl}sw.js`)
                .then( registration => {
                // Registration was successful
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
            })
            .catch(err => {
                // registration failed :(
                console.log('ServiceWorker registration failed: ', err);
            });
        }
    });

    The main function of the above code is to check whether the SW API is available in the navigator attribute of the window object. The window object represents the browser window. If SW is available in navigator, register SW as soon as the page loads.

    Although it’s easy to register an SW, we still encounter the problem of failing to register a service worker in some cases. Let’s take a brief look at the reasons why we can’t register an SW and how to solve it:

    • Your application cannot run under HTTPS. In the development process, you canlocalhostUse SW. However, if you deploy it on a website, you need to enable HTTPS.
    • The path of SW is incorrect.

    Update on reload is not checked.

    Service worker events

    In addition to the install and activate events, other events include message, fetch, sync, and push events.

    Add the following code to your SW to listen for lifecycle events (installation and activation):

    
    self.addEventListener('install', event => {
        console.log('[Service Worker] Installing Service Worker ...', event);
        event.waitUntil(self.skipWaiting());
    });
    self.addEventListener('activate', event => {
        console.log('[Service Worker] Activating Service Worker ...', event);
        return self.clients.claim();
    });

    The install callback calls the skipwaiting () function to trigger the activate event and tell the service worker to start working immediately without waiting for the user to browse or reload the page.

    The skipwaiting() function forces the waiting service worker to become the active service worker. self. The skipwaiting () function can also be used with self clients. Use with the claim () function to ensure that updates to the underlying service worker take effect immediately.

    In this case, self property represents the window object (that is, your browser window).

    Add to home button

    The add to home button allows users to install PWA on their devices. In order to actually install PWA with this button, you must define a fetch event handler in SW. Let’s go to sw JS to solve this problem.

    
    self.addEventListener('fetch', event => {
        console.log('[Service Worker] Fetching something ....', event);
        // This fixes a weird bug in Chrome when you open the Developer Tools
        if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
            return;
        }
        event.respondWith(fetch(event.request));
    });

    Service worker cache

    The strength of service worker lies in its ability to intercept HTTP requests. In this step, we use this option to intercept HTTP requests and responses and provide users with lightning fast responses directly from the cache.

    Pre caching during service worker installation

    When users visit your website for the first time, SW will start to install itself. In this installation phase, you can download and cache all pages, scripts and style files used by PWA. The following is SW JS file code:

    
    const CACHE_STATIC_NAME = 'static';
    const URLS_TO_PRECACHE = [
        '/',
        'index.html',
        'src/js/app.js',
        'src/js/feed.js',
        'src/lib/material.min.js',
        'src/css/app.css',
        'src/css/feed.css',
        'src/images/main-image.jpg',
        'https://fonts.googleapis.com/css?family=Roboto:400,700',
        'https://fonts.googleapis.com/icon?family=Material+Icons',
    ];
    self.addEventListener('install', event => {
        console.log('[Service Worker] Installing Service Worker ...', event);
        event.waitUntil(
            caches.open(CACHE_STATIC_NAME)
                .then(cache => {
                    console.log('[Service Worker] Precaching App Shell');
                    cache.addAll(URLS_TO_PRECACHE);
                })
                .then(() => {
                    console.log('[ServiceWorker] Skip waiting on install');
                    return self.skipWaiting();
                })
        );
    });

    This code uses the installation event and adds a URLs during the installation phase_ TO_ Precoche array. Once you call the open cache function (caches. Open), you can use cache Addall() function to cache the files in the array. Via event The waituntil () method uses JavaScript promise to know how long the installation takes and whether it is successful.

    The installation event calls self Skipwaiting() activates SW directly. If all files have been successfully cached, SW will be installed. However, if one of the files cannot be downloaded, the installation step will fail. In the chrome developer tool, you can check whether the cache (in cache storage) is used by URLs_ TO_ The static file population in the cache array.

    However, if you look at the network tab, the files are still obtained through the network. The reason is that although the cache is ready, we did not read the reference resources from the cache. Therefore, in order to complete this part of work, we must first listen to the fetch event of the application, then intercept and obtain resources from the cache. Let’s take a look at the following code:

    
    self.addEventListener('fetch', event => {
        console.log('[Service Worker] Fetching something ....', event);
        event.respondWith(
            caches.match(event.request)
                .then(response => {
                    if (response) {
                        console.log(response);
                        return response;
                    }
                    return fetch(event.request);
                })
        );
    });

    We use caches The match() function checks whether the incoming URL matches the resources that may exist in the current cache. If it matches, we will return the cached resource, but if the resource does not exist in the cache, we will continue to obtain the requested resource as usual.

    After the service worker is installed and activated, refresh the page and check the network tab again. Now, the service worker will intercept HTTP requests and immediately load the corresponding resources from the cache instead of making network requests to the server.

    Now, if we set the offline mode in the network tab, our applications can still be accessed normally.

    Background transmission

    Background fetch API is the background function of SW, which allows users to download large files, videos, music and other resources in the background. During the acquisition / transfer process, your user will not clear the transfer task even if he closes the tag or even closes the whole browser. When the user opens the browser again, the transfer process will resume. The API can also display the transmission progress to the user, and the user can cancel or pause the process.

    By default, the background transfer function is not available. You must use the URL( chrome://flags/#enable -Experimental web platform features) allows Chrome’s “experimental web platform features” option

    The following is an example of how to implement such a background transfer.

    In your index Add a button with ID “bgfetchbutton” to the HTML file

    
    <button>Store assets locally</button>

    Then, load the app. In the event handler JS to add code for performing background transfer

    
    window.addEventListener(‘load', () => {
    ...
           bgFetchButton = document.querySelector(‘#bgFetchButton');
           bgFetchButton.addEventListener(‘click', async event => {
             try {
                const registration = await navigator.serviceWorker.ready;
                registration.backgroundFetch.fetch(‘my-fetch', [new              Request(`${baseUrl}src/images/main-image-lg.jpg`)]);
             } catch (err) {
                console.error(err);
             }
         });
    ...
    });

    The above code starts the background transmission under the following conditions:

    • The user clicks the button with ID bgfetchbutton
    • SW registered

    The background transfer must be performed in an asynchronous function because the transfer process cannot block the user interface.

    Put into cache after transfer

    
    self.addEventListener(‘backgroundfetchsuccess', event => {
      console.log(‘[Service Worker]: Background Fetch Success', event.registration);   event.waitUntil(
       (async function() {
         try {
         // Iterating the records to populate the cache
           const cache = await caches.open(event.registration.id); const records =          await event.registration.matchAll(); const promises = records.map(async          record => {
             const response = await record.responseReady;
             await cache.put(record.request, response);
           });
           await Promise.all(promises);
         } catch (err) {
           console.log(‘[Service Worker]: Caching error');
         }
       })()
      );
    });

    This code consists of the following steps:

    • When the background fetch transmission is completed, your SW will receive the background fetch success event.
    • Create and open one with registration New cache with the same ID.
    • Through registration Matchall() gets all the records and iterates over them.

    Finally, through promise All (), implement all commitments.

    summary

    In this article, we discussed two basic components of PWA: the basic function introduction of manifest and service worker, because we have discussed HTTPS before https://www.cnblogs.com/powertoolsteam/p/http2https.html

    The above is the details of how to develop a progressive web application PWA. For more information about developing a progressive web application, please pay attention to other related articles of developeppaer!

    Recommended Today

    RabbitMQ study notes

    Table of contents Related concepts RabbitMQ Install RabbitMQ core part Hello World Work Queues release confirmation switch fanout exchange (pub/sub) direct exchange topic exchange dead letter queue delay queue Release Confirmation Advanced The switch receives the message confirmation callback Fallback message to producer when switch is not routable Backup switch other idempotency priority queue lazy […]