What do you need to know before a web application (PWA)?

Create a Manifest.json
PWA Manifest.json file 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 your application manifest Create a Manifest.json file in a directory at the same level as the index.html file. After the manifest file is created, add the reference link of the manifest file to index.html.





















1

Manifest attribute introduction Manifest has many configuration attributes, and then we will give a brief introduction to the attributes

name, short_name: Specify 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.
l display: The display attribute specifies the display mode of the web application. It has four values ​​for configuration: fullscreen, standalone, minimal-ui and browser, but the commonly used attributes are fullscreen and standalone.
fullscreen: Full screen display
standalone: ​​The application opened in this mode does not appear in the address bar of the browser, so it looks more like a native application
minimal-ui, browser: It is not much different from using a browser to visit.
l orientation: Control the display direction of the web application and prohibit the phone from turning the screen.
l 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, it can be combined into the application's Splash Screen.
l theme_color: Define the default theme color of the application.
l description: Set a description of the application.
The above are some descriptions of the properties of the pwa manifest file. We can add the manifest file by placing the completed manifest file in the same level directory as the index.html file.

Open Chrome Developer Tools-Application-Manifest, check whether the added manifest file has been loaded, if there is no information as shown 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 Workers can implement common functions of native applications such as offline caching, message push, and silent update in browser-based web applications to provide web applications with a better and richer experience.

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

Service Worker Life Cycle
For Service Worker, the basic setup steps are as follows:

The SW should be registered first. If the SW is already registered, the browser will automatically start the installation according to the installation event.
After installing SW, it will receive activation events. This activation event can be used to clean up resources used in earlier versions of SW.

The actual operation should first create an empty file named sw.js at the same level as index.html. Then add a base tag to the index.html file, as follows:

1

Finally, add the following code to register SW in src/js/app.js. This code will be activated during the page "loading" process.

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 property of the window object. The window object represents the browser window. If SW is available in navigator, register SW immediately when the page loads.

Although registering a SW is very simple, in some cases we still encounter the problem of not being able to register a Service Worker. Let's take a brief look at the reasons for not being able to register SW and how to solve it:

Your application cannot run under HTTPS. During development, you can use SW through localhost. But if it is deployed 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 install and activate events, other events include message, fetch, sync, and push events.

Add the following code to your SW to monitor life cycle 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(); }); install callback calls skipWaiting() function to trigger the activate event and tell The Service Worker starts 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. The self.skipWaiting() function can also be used with the self.clients.claim() function to ensure that updates to the underlying Service Worker take effect immediately.

In this case, self-property represents the window object (ie your browser window).

Add to home screen button
"Add to home screen 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 solve this problem in sw.js.

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 'IF-only-cached' && event.request.mode == 'Same-Origin') {! return; } event.respondWith (FETCH (event.request)); }); Service Worker cache Service Worker The power of is 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 a user visits 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 the sw.js file code to complete this work:

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 installation events and is in the installation phase Added an array of URLS_TO_PRECACHE. Once the open cache function (caches.open) is called, you can use the cache.addAll() function to cache the files in the array. Use the JavaScript promise through the event.waitUntil() method to know how long the installation will take and whether it is successful.





The installation event will call self.skipWaiting() to activate SW directly. If all files have been successfully cached, SW will be installed. But if one of the files cannot be downloaded, the installation step will fail. In Chrome Developer Tools, you can check whether the cache (in Cache Storage) is filled with static files in the URLS_TO_PRECACHE array.

However, if you look at the Network tab, the file is still obtained via the network. The reason is that although the cache is ready, we have not read the reference resource from the cache. So in order to complete this part of the work, we must first listen to the application's fetch event, and then intercept and obtain resources from the cache, let us 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 the caches.match() function to check whether the incoming URL is consistent with the current cache Resource matching. If it matches, we return the cached resource, but if the resource does not exist in the cache, we continue to get the requested resource as normal.












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

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

Background Transfer
Background Fetch API is back-office functions SW, which allows users to download large files, video and music and other resources in the background. During the acquisition/transmission process, even if your users close the tab, or even close the entire browser, the transmission task will not be cleared. When the user opens the browser again, the transfer process will resume. This API can also display the progress of the transfer to the user, and the user can cancel or pause the process.

By default, the background transfer feature is not available, you must allow chrome's "Experimental Web Platform features" option through the url (chrome://flags/#enable-experimental-web-platform-features)

The following is an example of how to implement this type of background transfer.

Add a button with ID "bgFetchButton" to your index.html file

1
Store assets locally

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( )]); } catch (err) { console.error(err); } }); }); The above code starts under the following conditions Perform background transfer:





${baseUrl}src/images/main-image-lg.jpg






The user clicks the button whose ID is bgFetchButton
SW is registered. The
background transfer must be performed in an asynchronous function, because the transfer process cannot block the user interface.

Put into the cache after the transfer is complete

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’);
}
})()
);
});
1 Longhua Avenue http://www.kinghill.cn/LongHuaDaDao1Hao/index.html

Guess you like

Origin blog.csdn.net/weixin_45032957/article/details/108599773