Service Worker implements offline applications

How to make a web page accessible offline?

The front-end cache

Introduction to the

  1. HTTP caching,HTTP caching is always started on the second request, mainly by setting the request header

    • Strong cache:Strong caching is controlled by using the Expires or cache-Control fields in the HTTP return header to indicate the Cache time of the resource. The status code 200 (from Cache) is directly fetched from the Cache without making a request
      • Expires
      • Cache-Control
    • Negotiation cache:Negotiation cache is to determine whether the cache resource is available by the server, so the client and server side through some identification to communicate, so that the server can determine whether the requested resource can cache access status code 304 (Not Modified) through the server to tell whether the cache is available
      • Last-Modify/If-Modify-Since
      • ETag/If-None-Match
  2. Browser cache

    • localStorage
      • Design an API to allow localStorage to expire by specified time?
    • sessionStorage
    • cookie
      • HttpOnly :true If the httpOnly attribute is set in the cookie, the JS script will not be able to read the cookie information, which can effectively prevent XSS attacks to steal the cookie content
      • The Secure:true property specifies that cookies can only be sent to the server over HTTPS
      • Domain: Different subdomains can be used to solve cross-domain problems
      • WithCredentials: True Indicates whether credentials are required for cross-domain requests in order for the server to get your cookies
  3. The cache location

    • The service worker has free control over which files to cache, how to match the cache, how to read the cache, how to cache the orderly registration, listening, HTTPS
    • Once we close the Tab page, the cache in Memory is freed
    • The Disk cache reads data slowly
    • Push cache exists only in sessions
  4. Impact of User behavior

    • Enter the address in the address bar
      • Check whether there is a match in the disk cache. If no match is found, a network request is sent
    • Normal Refresh (F5)
      • Use Memory cache first, Disk cache second
    • Forced to refresh
      • CTRL +F5 browser does not use caching

advantages

Caching is a simple and efficient way to optimize performance. A good caching strategy can shorten the distance of web page request resources, reduce latency, and reduce bandwidth and network load because cached files can be reused

Service Worker

###1. Add Service Worker to the profile

There is less content without Service Worker and no obvious difference is found

  1. How to open the Web App

    • Browser bookmarks, URL favorites
    • Browser Address Enter the web address
    • Search engine
  2. The Web App Manifest is a JSON file

    • Add to the home screen
      • Start animation, desktop icon, browser address bar immersive experience
      • main.m.taobao.com

  3. What is a Service Worker

    • It is a special Web worker. The browser runs in the background in a separate thread from the main thread of the web page. It usually does some performance-consuming calculations, and renders and calculations are separated to avoid blocking
  4. The Service Worker characteristics

    • The manipulation DOM cannot be accessed directly
    • Wake up directly when needed and sleep automatically when not needed
    • Offline cache content developers can control
    • Once installed, it lives forever unless manually uninstalled
    • Must work in HTTPS environment (except local environment), security requirements
    • Promise was widely used
  5. Service Worker scope. Multiple Service workers of different scopes are allowed to be registered in the same domain

    Url Registered address scope
    /static/sw.js /static/
    /static/sw.js /static/child/

    Incorrect example 1. Not homologous domain 2. 3-level domain that exceeds the default left and right domain

    Url Registered address scope
    /static/sw.js other.com/
    /static/sw.js /static/child/
    /static/sw.js /assets

Sw is based on HTTPS. Since request interception is involved in service workers, HTTPS protocol must be used to ensure security. Localhost is fine for local debugging ###3

Life cycle www.jianshu.com/p/8770ebcb6…

  1. Install, installation
  2. Waiting, waiting for
  3. Activate – activated

###4. Debugging methods

  1. Offline Simulates the network disconnection operation
  2. Update on Reload is reinstalled every time – enabled, easy to develop
  3. The bypass for network bypasses the service worker agent and skips the sw
  4. Remove the unregister sw

###5. Use method

  1. Service worker files can only be cached for a maximum of 24 hours by the browser to avoid destruction. Sw.js files cannot be cached by HTTP
  2. Pay attention to storage space
    • CacheStorage is not an infinite cache. You need to manually manage the cache, clean up the cache in time, control the amount of dynamic content, and use the LRU algorithm to eliminate the cache
For a typical project structure, run the NPM run build front end to generate the dist directory and run bash Serviceworker.sh to replace CACHE_VERSION/CONFIG project dist CSS img js index.html sw.js public index.html sw.js src README.md serviceWorker.sh ...Copy the code
// sw.js
let VERSION = CACHE_VERSION; / / version number
let CACHE_NAME = "cache_v" + VERSION;
let CACHE_URLS = [
  CONFIG // Cache file path
];

/** * cache in cacheStorage **@param {Request} Req Request object *@param {Response} Res Response object */
function saveToCache(req, res) {
  return caches.open(CACHE_NAME).then(cache= > cache.put(req, res));
}

/** * precache **@return {Promise} Cache successful promise */
function precache() {
  return caches.open(CACHE_NAME).then(function (cache) {
    return cache.addAll(CACHE_URLS);
  });
}

/** * Clear expired cache **@return {Promise} promise* /
function clearStaleCache() {
  return caches.keys().then(keys= > {
    keys.forEach(key= > {
      if (CACHE_NAME !== key) {
        caches.delete(key);
      }
    });
  });
}

/** * request and cache content **@param {Request} req request
 * @return {Promise}* /
function fetchAndCache(req) {
  return fetch(req).then(function (res) {
    saveToCache(req, res.clone());
    return res;
  });
}

// Download the new cache
self.addEventListener("install".function (event) {
  event.waitUntil(precache().then(self.skipWaiting));
});

// Delete the cache
self.addEventListener("activate".function (event) {
  event.waitUntil(Promise.all([self.clients.claim(), clearStaleCache()]));
});

self.addEventListener("fetch".function (event) {
  // Apply the HTTP cache policy to CDN resources of the same origin
  if (newURL(event.request.url).origin ! == self.origin) {return;
  }

  if (event.request.url.includes("/api/movies")) {
    event.respondWith(
      fetchAndCache(event.request).catch(function () {
        returncaches.match(event.request); }));return;
  }

  event.respondWith(
    fetch(event.request).catch(function () {
      returncaches.match(event.request); })); });Copy the code
# serviceWorker.sh

#! /bin/bash
rm -f serviceWorker.txt
function readfile ()
{
# here is the key symbol under ESC
  for file in `ls The $1`
  do
# -d indicates a directory/subfolder
    if [ -d The $1"/"$file ]
    then
# If subfolders are recursive
      readfile The $1"/"$file
    else
Otherwise, you can read the address of the file
     /bin/echo -n \"The $1"/"$file\"\, >> serviceWorker.txt
Basename is the key to extract the file name
   #echo `basename $file` >> fileName.txt
   fi
  done
}
This is used to run the function
folder="./dist"
readfile $folder

sed -i ' ' 's/\.\/dist//g' serviceWorker.txt
sed -i ' ' '$s/,$//' serviceWorker.txt

filepath=$(cd "$(dirname "$0")"; pwd)  

getFileName=$(cat "${filepath}/serviceWorker.txt")

Replace the CONFIG cache static resource path in /dist/sw.js
sed -i ' ' "s:CONFIG:${getFileName}:g" ${filepath}/dist/sw.js
time=$(date "+%Y%m%d%H%M")
# Replace CACHE_VERSION in /dist/sw.js with the cache version number
sed -i ' ' "s:CACHE_VERSION:${time}:g" ${filepath}/dist/sw.js
Copy the code

###6. Cache strategy

  1. staleWhileRevalidate
    • If there is no Cache in the first place, the network request will be made and the result will be updated. This is a very secure policy for users
    • Cons: Still takes up bandwidth
  2. networkFirst
    • In this strategy, when the request route is matched, the network first policy is adopted, that is, the return result of the network request is first tried, and if the result of the network request is received, the result is returned to the client and written to the Cache. If the network request fails, the last cached Cache result will be returned to the client. This strategy is generally applicable to the request whose return result is not fixed or requires real-time performance, so as to take the bottom line for the network request failure
  3. cacheFirst
    • If there is no result in the Cache, the network request will be made, the network request will be fetched, the result will be updated to the Cache, and the result will be returned to the client. This strategy is more suitable for the request that the results do not change much and the real-time requirement is not high
  4. NetworkOnly (directly using network requests, no caching)
    • The more direct policy directly forces the normal network request and returns the result to the client. This policy is more suitable for the request with high real-time requirements
  5. CacheOnly (directly using caching)
    • This strategy is also more direct, directly use the Cache results, and return the results to the client, this strategy is more suitable for static resource requests that do not change once online

community

  1. Workbox is an official Google tool
  2. Servier WorkermDN Api and browser compatibility
  3. Vue API document uses service worker to achieve offline access,vue API document service-worker source code can be interested in students can see
  4. Language finch online documentation