Html:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8" /> <title>HTML5 Thread Interaction Examples</title> <Scripttype= "Text/javascript"src= "Mainthread.js"> </Script></Head><Body> <inputtype= "text"ID= "Inputedinteger" /> <inputtype= "button"value= "Click let the main thread send this value to background thread 1"onclick="Html5worker()" /> <PID= "Result"></P> </Body> </HTML>
Mainthread. Js
functionHtml5worker () {//determine if the browser supports if(typeof(Worker) = = "Undefined") {Console.log ("Sorry your browser does not support worker"); return; } //Create a Web worker instance varWorker1 =NewWorker ("Thread1.js"); varIntegerinput = document.getElementById ("Inputedinteger"). Value; varnum = parseint (integerinput, 10); //Cross document messages are transmitted across documents Messaging. //PostMessage send a message to Thread1Worker1.postmessage (num + "I am the main thread value I will send to Thread1"); //OnMessage Event Listener //when a web worker passes a message, the code in the event listener is executed. Data from Event.data is stored in the event.data. Worker1.onmessage =function(event) {//get information from background thread 1 (thread1) vardata =Event.data; varWorker2 =NewWorker ("Thread2.js"); Worker2.postmessage (Data+ "I am the main thread value I will send to Thread2"); Worker2.onmessage=function(event) {document.getElementById ("Result"). InnerHTML =Event.data; } };}
Thread1.js
function (event) { var result = Event.data + "I am the value received by Thread1 I will return"; Console.log ("Thread1"); //
Thread2.js
function (event) { // get data from the mainline Cheng var result = Event.data + "I am the value thread2 receive I will return" ; Console.log ("thread2"); // postMessage (result);
Operation Result:
Note that you have to publish to the server to run or otherwise appear:
Uncaught securityerror:failed to construct ' Worker ': Script at ' xxxxthread1.js ' cannot is accessed from Origin ' null '.
Summarize:
1: Create worker instance and pass the corresponding JS file
2: Send Message postMessage ()
3: Listening Message onmessage
4: Stop Terminate () method
5:onerror Error exception
You can also listen to messages in the following ways.
// Google or IE Register events if (typeof Window.addeventlistener! = ' undefined ') { Window.addeventlistener (false ); Else if (typeof window.attachevent! = ' undefined ') { window.attachevent (' onmessage ', Messagechange); }