diff --git a/src/main.js b/src/main.js index de73174..b8729a5 100644 --- a/src/main.js +++ b/src/main.js @@ -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)