Refactor web worker implementation in main.js

This commit is contained in:
2023-11-12 04:18:01 +08:00
parent 53b82a8006
commit c4db8b5e1e

View File

@ -1,18 +1,15 @@
if (typeof SharedWorker === "undefined") {
alert('当前浏览器不支持webworker')
if (typeof SharedWorker !== "undefined") {
const worker = new SharedWorker('/src/worker.js')
worker.port.onmessage = (e) => {
console.log('worker.port.onmessage:', e.data)
}
worker.port.start()
const button = document.createElement('button')
button.innerText = 'click'
button.onclick = () => {
worker.port.postMessage('hello, worker')
}
document.body.appendChild(button)
} else {
console.log('当前浏览器不支持webworker')
}
// 检查是否存在其它标签页, 如果存在不必建立 websocket 连接, 如果不存在, 则建立 websocket 连接
const worker = new SharedWorker('/src/worker.js')
worker.port.onmessage = (e) => {
console.log('worker.port.onmessage:', e.data)
}
worker.port.start()
const button = document.createElement('button')
button.innerText = 'click'
button.onclick = () => {
worker.port.postMessage('hello, worker')
}
document.body.appendChild(button)