Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

service-worker serviceWorker 相关 #648

Open
cisen opened this issue Sep 10, 2019 · 0 comments
Open

service-worker serviceWorker 相关 #648

cisen opened this issue Sep 10, 2019 · 0 comments
Labels

Comments

@cisen
Copy link
Owner

cisen commented Sep 10, 2019

其中service worker一般作为web应用程序、浏览器和网络(如果可用)之间的代理服务。他们旨在创建有效的离线体验,拦截网络请求,以及根据网络是否可用采取合适的行动,更新驻留在服务器上的资源。他们还将允许访问推送通知和后台同步API。用来构建PWA 应用
使用service-worker前,我们必须要先在主进程中注册它,然后才能在service-worker进程中编写逻辑。

主进程

//index.js
if ("serviceWorker" in navigator) {
    // Use the window load event to keep the page load performant
    window.addEventListener("load", () => {
      navigator.serviceWorker.register("/service-worker.js").then(registration=>{
        console.log("register succces...")
      }, err=>{
        console.log("register error...",err)
      });
    });
  }

service-worker进程

//service-worker.js
console.log('Hello from service-worker.js');

service-worker的语法简介
在service-worker.js中,self/this 表示 ServiceWorkerGlobalScope, 即全局的serviceworker工作环境,相当于在主进程中的window。在此文件中,js的其他api无法使用,如DOM,BOM操作等,但是大部分的js api可用,同时ES6也可以使用。

在service-worker中可以定义监听事件,然后在对应事件中进行逻辑处理。

具体api可查看 service worker MDN

service-worker进程的执行流程

  1. 首先在主进程中开始注册,调用register方法,进入sw进程,在sw进程中判断如果还没有安装service worker.js,则触发install事件。开始安装
  2. 一旦sw进程安装完成,会通知主进程register成功。
  3. 接着在sw进程 触发到activate事件。
  4. 如果已经安装过service-worker.js文件,则在注册时会发现并跳过install事件,直接进入注册成功,然后触发activate事件。
  5. 然后开始在sw进程中通过fetch事件,来监听http请求,并对请求和响应进行缓存。
//在service worker中监听install
this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        '/sw-test/',
        '/sw-test/index.html',
        '/sw-test/style.css',
        '/sw-test/app.js',
        '/sw-test/image-list.js',
        '/sw-test/star-wars-logo.jpg',
        '/sw-test/gallery/',
        '/sw-test/gallery/bountyHunters.jpg',
        '/sw-test/gallery/myLittleVader.jpg',
        '/sw-test/gallery/snowTroopers.jpg'
      ]);
    })
  );
});

除了 install之外,还有 activate,message,fetch,sync,push等事件。

打开chrome浏览器的application->service workers,会看到
image

可以看到status为 actived and is running,表明service-worker已经安装成功了。

在service-worker中通过监听事件,然后编写对应的逻辑并不是一件容易的事,尤其对于文件缓存,可能npm run build后,名称随时会变。

所以chrome官方推出了wokbox框架

clipboard.png

wokbox 是用于向web应用程序添加离线支持的JavaScript库。

@cisen cisen added the pwa label Sep 10, 2019
@cisen cisen changed the title service-worker 相关 service-worker serviceWorker 相关 Dec 26, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant