HTML:
mainthread.JS
thread1.js
thread2.js
運作結果:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL5UDNxATM4UjMxAjM5ITOwgTMwIzLcZDM0EDMy8CXvZmbp9CXt92YuUGZvNWatFWbuU2Zh1Wavw1LcpDc0RHaiojIsJye.png)
注意的是要釋出到伺服器才能運作否則出現:
Uncaught SecurityError: Failed to construct ‘Worker‘: Script at ‘xxxx‘ cannot be accessed from origin
‘null‘.
總結 :
1:建立worker執行個體并傳遞對應的js檔案
2:發送消息 postMessage()
3:監聽消息 onmessage
4:停止terminate()方法
5:onerror錯誤異常
監聽消息也可以用下列方式.