registerServiceWorker创建的React项目中的registerServiceWorker作用?

1、安装create-react-app:npm/cnpm installl create-react-app -g

2、创建项目:create-react-app my-first-app

3、此时项目里包含一个registerServiceWorker.js文件,作用是什么呢?

  service worker是在后台运行的一个线程,可以用来处理离线缓存、消息推送、后台自动更新等任务。registerServiceWorker就是为react项目注册了一个service worker,用来做资源的缓存,这样你下次访问时,就可以更快的获取资源。而且因为资源被缓存,所以即使在离线的情况下也可以访问应用(此时使用的资源是之前缓存的资源)。注意,registerServiceWorker注册的service worker 只在生产环境中生效(process.env.NODE_ENV === 'production'),所以开发的时候,可以注释掉,当然生产模式下,也可以不用这个功能。

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

参考:

1、https://segmentfault.com/q/1010000010667462

原文地址:https://www.cnblogs.com/shengulong/p/8425311.html