worker实践

-

参考博客:http://www.ruanyifeng.com/blog/2018/07/web-worker.html

work是用来开启子线程的,我们可以把一些计算量大的程序放到子线程去执行,去提升性能。

下面是一个简单的demo(在vue中使用的)

因为worker脚本必须来自网络,而且和主线程必须在同一域名下。于是把worker脚本放在了public目录下:

将worker相关方法封装成一个类:

class WorkerClass{
  constructor(){
    // ${window.location.origin}/selfWorker.js
    this.url = `/js/selfWorker.js`;
    console.log(this.url, 'this.url');
    this.worker = new Worker(this.url);
  }
  postMessage(message){
    if(this.worker){
      this.worker.postMessage(message);
    }
  }
  onmessage(cb){
    this.worker.onmessage = (event) => {
      cb(event);
    }
  }
  close(){
    this.postMessage('STOP');//通知子线程关闭
    this.worker.terminate();
    this.worker = null;
  }
  onerror(cb){
    this.worker.onerror = (event) => {
      cb(event);
    }
  }
}

window.W = WorkerClass;

在public/index.html中引入

<script src="/js/worker.js"></script>

页面中代码:

let worker = new window.W();
    worker.onerror(err => {
      console.log(err, '子线程发生错误');
    })
    worker.postMessage('hello');
    worker.onmessage(e => {
      console.log(e.data, '主线程接收到的消息');
    })
    // worker.close()
    worker.postMessage('hello2');

子线程代码:

self.addEventListener('message', function (e) {
  let { data } = e;
  switch(data){
    case 'STOP':
      this.self.close();//子进程关闭
    default:
      break;
  }
  console.log(data, '子线程接到的消息');
  self.postMessage('You said: ' + data);
}, false);

 

 

 

 

-

posted @ 2021-10-17 21:11  古墩古墩  Views(61)  Comments(0Edit  收藏  举报