一、作用
javascript 是单线程执行,web worker可创建多线程模型,那么主线程只负责UI之类的,可提高性能
二、web worer用法
主线程
var parent = new Worker('worker.js') //向子线程传递消息 parent.postMessage('来自主线程的消息') //获取子线程返回的消息 parent.onmessage = function(event){ console.log(event.data)
//关闭子线程
worker.terminate() }
子线程
需要添加个监听函数,监听主线程的消息
_self.addEventListener('message',fucntion(e){ console.log('收到到主线程的消息:',e.data)
//关闭线程
_self.close() })
三、注意要点
1、子线程有自己作用域,不能获取window(主线程)的dom结构等,this不指向window
2、worker无法读取本地文件,即他所加载的脚本只能来自网络
3、分配给子线程的脚本,必须与主线程脚本同源
感谢:http://www.ruanyifeng.com/blog/2018/07/web-worker.html