【问题标题】:How service worker works?Service Worker 是如何工作的?
【发布时间】:2018-10-03 08:14:43
【问题描述】:

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

现在这是我的 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();
    });
  }
}

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

请帮忙!!!

【问题讨论】:

    标签: reactjs service-worker progressive-web-apps service-worker-events


    【解决方案1】:

    基于documentation:

    服务工作者是一种网络工作者。它本质上是一个 与主浏览器线程分开运行的 JavaScript 文件, 拦截网络请求、缓存或检索资源 缓存,并传递推送消息。

    从上面的示例代码中,您正在使用 react 框架构建带有 create-react-app 的 PWA。它将通过允许开发人员构建 React 应用程序而无需或很少构建配置来消除所有这些。

    Build a realtime PWA with React

    服务工作者代码基本上注册了一个服务工作者 反应应用程序。我们首先检查应用程序是否通过 isLocalhost const 值从 localhost 提供服务,该值将返回真值或假值。 register() 函数有助于注册 仅当 React 应用程序处于生产模式并且 如果浏览器支持 Service Worker。

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

    unregister() 函数 有助于注销 service worker。

    【讨论】:

    • 感谢您的回答。本论坛无人回复
    猜你喜欢
    • 2020-11-16
    • 2018-07-21
    • 2021-12-12
    • 2019-01-07
    • 2018-11-25
    • 1970-01-01
    • 2016-10-10
    • 2020-01-04
    • 1970-01-01
    相关资源
    最近更新 更多