web worker可以让一个web application在与主线程分离的后台线程中运行一个脚本操作。比如把耗时的任务放到web worker内去执行,从而可以让主线程的运行不被阻塞。

web worker兼容性如下:
web worker兼容性

由于web worker位于外部文件中,所以无法访问主线程中的window,document,parent的对象。

web worker与主线程通过postMessage来发送消息,onmessage来接受消息,terminate方法来终止web worker。同时,传递的数据是副本传递而不是引用传递,但是在web worker中可以使用window对象中一些默认的方法和属性,比如websockets,indexedDB等。

简单的demo:
首先命名js文件为ww.js,内部代码如下:

1
2
3
onmessage = (e) => {
postMessage(e.data += 1)
}

然后在主线程中创建web worker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>

<body>
<button id="wBtn" onclick="calculate()">0</button>
<script>
const wBtn = document.querySelector('#wBtn')
const ww = new Worker('./ww.js')

const calculate = () => {
const btnInnerText = wBtn.innerText
ww.postMessage(+btnInnerText)
}

ww.onmessage = (e) => {
wBtn.innerText = e.data
}
</script>
</body>

</html>

点击按钮效果如下:
点击效果