Web Worker 的作用,就是为 JavaScript 创造多线程环境,允许主线程创建 Worker 线程,将一些任务分配给后者运行。
一、Web Worker 具体用法
import React, { Component } from 'react';
import worker_script from './worker-script';
export default class PageHome extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
const worker = new Worker(worker_script);
console.log(worker);
worker.onmessage = function (event) {
console.log(`Received message ${event.data}`);
};
// worker.postMessage('dadada')
}
}
worder-script.js
const workercode = () => {
self.onmessage = function (e) {
console.log('Message received from main script');
let workerResult = `Received from main: ${e.data}`;
console.log('Posting message back to main script');
self.postMessage(workerResult);
};
self.postMessage('workerResult');
};
let code = workercode.toString();
code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));
const blob = new Blob([code], { type: 'application/javascript' });
const worker_script = URL.createObjectURL(blob);
export default worker_script;
二、注意事项
1、非同源限制,主线程代码与Worker线程代码必须同源才能一起正常工作
2、Worker线程任务需要等待主线程任务结束才能进行
3、可以主动关闭Worker线程。如果是多页应用的话,离开了Worker页面,Worker 也会停止工作
4、脚本限制,worker线程不能执行alert 、confirm ,但可以使用?XMLHttpRequest ?对象发出ajax请求
|