constfirst=document.querySelector('#number1');constsecond=document.querySelector('#number2');constresult=document.querySelector('.result');if (window.Worker) {constmyWorker=newWorker("worker.js");first.onchange=function() {myWorker.postMessage([first.value,second.value]);console.log('Message posted to worker'); }second.onchange=function() {myWorker.postMessage([first.value,second.value]);console.log('Message posted to worker'); }myWorker.onmessage=function(e) {result.textContent =e.data;console.log('Message received from worker'); }} else {console.log('Your browser doesn\'t support web workers.')}
上面的例子创建了一个woker,并向worker post了一个消息。
再看一下worker.js的内容是怎么样的:
onmessage=function(e) {console.log('Worker: Message received from main script');constresult=e.data[0] *e.data[1];if (isNaN(result)) {postMessage('Please write two numbers'); } else {constworkerResult='Result: '+ result;console.log('Worker: Posting message back to main script');postMessage(workerResult); }}
importScripts(); /* imports nothing */importScripts('foo.js'); /* imports just "foo.js" */importScripts('foo.js','bar.js'); /* imports two scripts */importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
Web Workers的分类
Web Workers根据工作环境的不同,可以分为DedicatedWorker和SharedWorker两种。
var first =document.querySelector('#number1');var second =document.querySelector('#number2');var result1 =document.querySelector('.result1');if (!!window.SharedWorker) {var myWorker =newSharedWorker("worker.js");first.onchange=function() {myWorker.port.postMessage([first.value,second.value]);console.log('Message posted to worker'); }second.onchange=function() {myWorker.port.postMessage([first.value,second.value]);console.log('Message posted to worker'); }myWorker.port.onmessage=function(e) {result1.textContent =e.data;console.log('Message received from worker');console.log(e.lastEventId); }}