The introduction

PWA(Progressive Web Apps) has been very popular in the past two years. What are its advantages?

  • You can generate small desktop ICONS without opening a browser, facilitating user access
  • Network cache is used to improve the speed of page access to achieve progressive page access or even offline access to improve user experience
  • Implement the push function similar to app and generate system notification to push to users

These advantages are enough to attract a large number of developers to explore and apply it. After all, for Web applications, user experience is the highest standard to test the quality of Web applications, and these advantages of PWA are exactly what developers have been pursuing in the development

Service Worker

Service worker is the core to realize PWA. Service worker is an independent browser thread, which will not block the execution thread of the current program. Through service worker, functions such as page offline access and user message push can be realized

The life cycle

The life cycle of a service worker is completely independent of a web page. Therefore, to use a service worker in a web page, you need to register first, and then the browser will start the installation steps in the background. In general, we need the service worker to cache some static files. Therefore, during the installation process, the specified static files will be cached. If the cache is successful, the service worker will be successfully installed; if any file cache fails, the service worker will fail to be installed and will try again at the next restart. Let’s look at a specific lifecycle diagram (source: developer.mozilla.org/zh-CN/docs/…) :

Simple application

It seems that the above introduction, is not itching to try? The following is a simple example of using the service worker to cache CSS and JS files in the page:


      
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <link rel="stylesheet" type="text/css" href="/cache1.css">
    <title>pwa</title>
  </head>
  <body>
    <div id="app">test1</div>
    <! -- built files will be auto injected -->
    <script src='/cache1.js'></script>
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load'.function () {
          navigator.serviceWorker.register('/sw.js').then((registration) = > {
            console.log('Service Worker Registration')
          }, (err) => {
            console.log(err)
          })
        })
      }
      self.addEventListener('fetch', () = > {console.log('ss')})</script>
  </body>
</html>
Copy the code

Sw. Js:

var cacheName = 'my-cache'
var cacheList = ['/cache1.css'.'/cache1.js']
self.addEventListener('install'.function(event) {
  event.waitUntil(
    // Store files to be cached in caches after successful installation
    caches.open(cacheName).then(function (cache) {
        return cache.addAll(cacheList)
    })
  )
});
// Listen on service worker fetch
self.addEventListener('fetch'.function (event) {
  event.respondWith(
    caches.match(event.request)
        .then(function(response) {
            // A matching request is found in the cache and returned from the cache
            if (response) {
                console.log(response)
                return response;
            }
            // No request found in cache, continue network request
            returnfetch(event.request); })); })Copy the code

As shown in the previous example, cache1.js and cache1.css are cached in the page request using the service worker, and then the page is refreshed. The page request looks like this:

portal

The vue – cli3 pwa

The latest scaffolding of Vue integrates the plug-in of PWA, which makes the implementation of PWA more simple. You only need to configure the PWA attribute in the vue.config.js file to automatically generate the corresponding service-worker.js configuration file. Portal, the core of which is the integration of Workbox developed by Google team. For more detailed PWA configuration, please refer to: Portal, which contains all the configuration items of Workbox. The runtimeCaching attribute provides five caching strategies:

  • CacheFirst: Priority is given to data in the cache. If not, the network is requested and an error is reported if the network fails
  • CacheOnly: Only fetched from the cache. If not, an error is reported
  • NetworkFirst: the IP address is preferentially obtained from the network. If the IP address is not obtained from the cache, an error is reported if the IP address fails to be obtained from the cache
  • NetworkOnly: The value is obtained only from the network. If the value is not obtained, an error is reported
  • StaleWhileRevalidate: Fetch data from both the network and the cache, if the cache is available, otherwise request it from the network, while the cache is updated as the network requests

More detailed caching strategies can refer to the portal, the caching strategies also need to pay attention to a problem is the same origin policy problems, usually workbox won’t cache cross-domain resource request, because the cross-domain resource in the cache, undetectable workbox cross-domain request is successful, if it fails, the user will not be able to obtain the response data, However, under NetworkFirst and StaleWhileValidate strategies, cross-domain resources can be cached because the cache is updated periodically, and even if a request fails, the cache is short-lived. For details, see portal

compatibility

Vue scaffolding is disabled on ios by default when integrating with ServiceWorker. It is not supported until ios 11.3. For details, see: Portal

conclusion

PWA is indeed a very popular technology at present, because it improves the experience of Web applications and even reaches the same level as the experience of native apps. However, its problem is compatibility. I believe that if the compatibility problem is solved, this technology will be widely promoted to practical applications. I hope this article can help you understand this technology. If there is a mistake or not rigorous place, welcome criticism and correction, if you like, welcome to praise.