H5 Offline storage – implemented using the serverWorker

Technology used for offline storage

serverWorker

ServiceWorker life cycle

  • The install event is triggered when the serviceWorker is successfully registered and is used to cache resources

  • The Activate event is triggered when the serviceWorker is activated and is used to delete old resources

  • The FETCH event is triggered when a request is sent and is used for caching operations or reading network resources

    Note:

  • If sw.js changes, the Install event refires

  • The Activate event is triggered after the install event, but if the serviceWorker already exists, it will wait until the serviceWorker terminates

  • You can skip the wait by using the self.skipWaiting() method and return a Promise object

  • The argument you can extend with the event.wautuntil () method is a Promise object that will not terminate the current lifecycle function until the promise ends, preventing the browser from stopping the lifecycle before a single action

  • ServiceWorker, when activated, takes effect the next time the page is refreshed and can immediately activate control via sell.clients.claim ()

// Register the serverWorker method in index.html
// Register when the page is finished loading
  window.addEventListener("load".() = > {
    // Ability test
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("./sw.js").then((res) = > {
        console.log(res); }); }});Copy the code
//serverWorker related events
self.addEventListener("install".(event) = > {
  console.log("install", event);
  //skipWaiting causes serviceworker to skip the wait and go directly to Activate
  //waitUntil skipWaiting is complete before entering activate
  event.waitUntil(self.skipWaiting());
});
self.addEventListener("activate".(event) = > {
  console.log("activate", event);
  // Indicates the control of the service worker to live immediately after it is activated
  event.waitUntil(self.clients.claim());
});
// The fetch event is triggered when the request is sent
self.addEventListener("fetch".(event) = > {
  console.log("fetch", event);
});
Copy the code

cache storage

The cacheStorage interface represents the storage of Cache objects and works with the Service worker to Cache resources

  • The cache API is similar to the operation of a database
    • Caches.open(cacheName).then(res=>{}), which opens the cache and returns a Promise to match the Cache object of cacheName, similar to connecting to a database
    • Caches. Key () returns a promise object, including all the cache keys
    • Caches. Delete (key) Deletes the corresponding cache based on the key
  • Cache object:
    • The cache interface provides a storage mechanism for cached pairs of Request/Response objects
    • Cache.put (req,res) treats the request as a key and stores the corresponding response
    • Cache.add (url) initiates a request based on the URL and stores the response
    • Cache.addall (urls) grabs an array of urls and stores the results
    • Cache.match (req) Gets the response corresponding to req

Implementing offline storage

Registered serverWorker

  // Register when the page is finished loading
    window.addEventListener("load".async() = > {// Ability test
      if ("serviceWorker" in navigator) {
        try {
          const registration = await navigator.serviceWorker.register(
            "./assets/sw.js"
          );
          console.log("Registration successful");
        } catch (error) {
          console.log("Registration failed", error); }}}); </script>Copy the code

Note:

  • Need to complete the page loading is registered to prevent competition with other resources, affect the normal use of the page.
  • ServerWorker can only be used in HTTPS or localhost

Setting the cache contents

Set the cache contents in the serverWorker install event

/ / sw. Js content
// Set the cache name to be used before version comparison deletes the cache
const CACHE_NAME = "cache_name_v1";
self.addEventListener("install".async (event) => {
  // Open a cache to get a cache object
  const cache = await caches.open(CACHE_NAME);
  // Wait for cache to store all resources
  await cache.addAll([
    "/"."/manifest.json"."/img/icon.png"."/css/index.css"."/js/index.js",]);// Wait for skipWaiting to end before entering activate
  await self.skipWaiting();
});
Copy the code

Clear the old cache

Activate checks if the stored versions are consistent and deletes the old cache if they are not

/ / sw. Js content
// Mainly clean up the old cache
self.addEventListener("activate".async (event) => {
  const keys = await caches.keys();
  // Delete the old resource
  keys.forEach((key) = > {
    if (key !== CACHE_NAME) {
      caches.delete(key);
    }
  });
  // Indicates the control of the service worker to live immediately after it is activated
  await self.clients.claim();
});
Copy the code

Reading Cache Offline

The FETCH event will be triggered when the request is sent. In the FETCH event, it determines whether the resource can be successfully requested. If the request can be successfully requested, it responds to the result of success

/ / sw. Js content
self.addEventListener("fetch".(event) = > {
  const req = event.request;
  event.respondWith(networkFirst(req));
});
// Network preference
async function networkFirst(req) {
  try {
    // Priority network reads the latest resources
    const fresh = await fetch(req);
    return fresh;
  } catch (e) {
    // read from the cache
    const cache = await caches.open(CACHE_NAME);
    const cached = await cache.match(req);
    returncached; }}Copy the code

Pay attention to

  • You can view the current Settings cache in the Browser developer Tools -> Application -> Cache