Service Worker 是如何工作的?

How service worker works?

我是渐进式网络应用程序的新手。我已经为我的 React PWA(渐进式网络)应用完成了 this 令人惊叹的教程和设置。

现在这是我的 serviceworker.js 文件

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    window.location.hostname === '[::1]' ||
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        checkValidServiceWorker(swUrl);
        navigator.serviceWorker.ready.then(() => {
        });
      } else {
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              console.log('New content is available; please refresh.');
            } else {
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl) {
  fetch(swUrl)
    .then(response => {
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

但是无法理解它是如何工作的?任何人都可以帮助这里注册,取消注册和其他功能吗?

请帮忙!!!

基于 documentation:

A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.

根据您上面的示例代码,您正在使用 React 框架通过 create-react-app 构建 PWA。它将通过允许开发人员在很少或没有构建配置的情况下构建 React 应用程序来消除所有这些问题。

Build a realtime PWA with React

The service worker code basically registers a service worker for the React app. We first check if the app is being served from localhost via the isLocalhost const value that will either return a truthy or falsy value. The register() function helps to register the service worker to the React app only if its in a production mode and if the browser supports Service workers.

registerValidSW() 函数将注册有效的 service worker 并负责状态(如果已安装)。 checkValidServiceWorker() 将检查是否可以找到 service worker。这将确保 service worker 存在,并且我们确实得到了一个 JS 文件。

The unregister() function helps to unregister the service worker.