Process: Worker------------ Àpostmessage----------------à task Stoke----------------àpostmessage---------------à event handler-------------------àonmessage---------- --------à return information.
Wrote a successful example: (There are two files, one is the home file, the other is the thread JS file)
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= ' Utf-8 '>5 <title>Title</title>6 <Script>7 window.onload=function(){8 9 Ten //Create a Thread object One A varworker=NewWorker ('Work.js'); //referencing a work.js file in a thread - - the //gets the return value of the worker process, which can be bound to an event handler through the OnMessage property . - //when the worker's PostMessage () method is called, the bound program is triggered - - Worker.onmessage=function(e) { + //process the received message - Console.log (e.data);//The OnMessage method of the page is used to process the data to the page; + A } at - AddEventListener ('Error', Errorhandle,true); //trigger This method when a thread error occurs - - Document.queryselector ('#btn'). AddEventListener ('Click', Stopworker,true); //binding terminating Threading Method - - //The importscripts () function loads the JS file into the worker process, such as loading hello.js importscripts (' hello.js '); in - to Worker.postmessage ('Hello webworker!'); + $ Panax Notoginseng /** * * Event handler function * * **/ - the functionErrorhandle (e) { + Console.log (e.message,e); A } the + - functionStopworker () { $ worker.terminate (); //terminating Threading Methods $ } - - the - Wuyi } the </Script> - </Head> Wu <Body> - <ButtonID= ' btn '>Dialog</Button> About </Body> $ </HTML>
{2: Thread file}
1 //This event is used to listen for the PostMessage event in the thread, which is used to receive the thread's loopback data.2 //and send the data back to the Web application page OnMessage listen to handle the data event3 4 /*Onmessage=function (e) {5 6 postMessage (E.data);//Send the data in the thread back to the page.7 8 }*/9 Ten One A //The second method uses Addeventlistenner to register background thread events; - -AddEventListener (' message ', Messagehandle,true); the - - functionMessagehandle (e) { - + postMessage (e.data); - +}
Web Worker Multithreading data