On Web Workers

Source: Internet
Author: User

First, Introduction

Web workers is a new technique in HTML5 that is used to implement background processing in Web applications. With the web workers you can create a background thread that does not affect foreground processing and create multiple child threads in this background thread. With the Web Workers, you can leave lengthy processing to the background thread to run, which solves the embarrassing situation where the user has to end the process before HTML5 because a process takes too long to jump out of a prompt user script to run too long.

Second, classification

There are two types of Web workers: a dedicated thread dedicated web worker, and a shared web worker. Dedicated web worker ends with the current page closing, which means that the dedicated web worker can only be accessed by the page that created it. The shared web worker that corresponds to it can be accessed by multiple pages. In JavaScript code, the "Worker" type represents dedicated web worker, and the "Sharedworker" type represents a shared web worker.

Third, the Worker object use

3.1 Common APIs

1. Create a Background thread:

In the worker class constructor, you will need the URL address of the script file to execute in the background thread as the parameter, and then create the worker object.

var worker=New worker ("Sumcalculate.js");

Note: A page or Window object cannot be accessed in a background thread. If you use a Window object or a Document object in a script file in a background thread, an error is raised.

2. Receive the message:

You can receive messages in a background thread by getting the OnMessage event handle to the worker object.

function (event) {    // processing received message };

3. Send a message:

Use the PostMessage method of the worker object to send a message to the background thread, which can be either text data or any JavaScript object (which needs to be converted to text data through the JSON object's Stringify method).

Worker.postmessage (message);

You can also receive and send messages inside a background thread by getting the OnMessage event and PostMessage method of the Worker object.

4. Terminate ()

The worker is terminated in the main thread and can no longer be used for message delivery. Note: Once terminate cannot be re-enabled, it can only be created separately.

Worker.terminate ();

5. Error ()

Error handling And the error message can be obtained through e.message.

function (e) {         // print error message          console.log (e.message);          // Break the connection     to a child thread     worker.terminate ();}

Iv. interacting with threads for data

1. front page JS code

varintarray=NewArray (100);varIntstr= ""; for(vari=0;i<100;i++) {Intarray[i]=parseint (Math.random () *100); if(i!=0) {Intstr+=";"; } intstr+=intarray[i];}varWorker=NewWorker ("Script.js"); Worker.postmessage (INTSTR); Worker.onmessage=function(event) {if(event.data!= ""){        varJ,k,tr,td,intarray=event.data.split (";"), table=document.getelementbyid ("Table");  for(vari=0;i<intarray.length;i++) {J=parseint (i/10,0); K=i%10; if(k==0) {TR=document.createelement ("tr"); Tr.id= "TR" +J;            Table.appendchild (TR); }Else{TR=document.getelementbyid ("tr" +j); } TD=document.createelement ("TD");            Tr.appendchild (TD); Td.innerhtml=intarray[j*10+K]; Td.style.backgroundColor= "Blue"; Td.style.color= "White"; Td.width= "30"; }    }}

2. Background thread code, placed in a JS file

 onmessage=function   var  data=event.data;     var  returnstr= ""  var  intarray=data.split (";"    );  for  (var  i=0;i< Intarray.length;i++ if  (parseint ( Intarray[i])%3==0 if  (returnstr!= "" Span style= "color: #000000;" >) {Returnstr  + = ";"             +=intarray[i]}} postMessage (RETURNSTR);}  

In this example, an array of integers is randomly generated on the page, then the positive array is passed into the thread, and the number that can be divisible by 3 in the array is selected and then displayed in the table in the page.

Five, thread nesting

Threads can be nested in a thread, so that we can split a larger background thread into sub-threads, each of which completes a relatively independent part of each sub-thread.

Example: This example modifies the example described earlier with data interaction with threads, putting the work of generating a random array into a background thread, and then using a sub-thread to pick a number that can be divisible by 3 in a random array. The code is as follows:

1. front page JS code

varWorker=NewWorker ("Script.js"); Worker.postmessage (" "); Worker.onmessage=function(event) {if(event.data!= ""){        varJ,k,tr,td,intarray=event.data.split (";"), table=document.getelementbyid ("Table");  for(vari=0;i<intarray.length;i++) {J=parseint (i/10,0); K=i%10; if(k==0) {TR=document.createelement ("tr"); Tr.id= "TR" +J;            Table.appendchild (TR); }Else{TR=document.getelementbyid ("tr" +j); } TD=document.createelement ("TD");            Tr.appendchild (TD); Td.innerhtml=intarray[j*10+K]; Td.style.backgroundColor= "Blue"; Td.style.color= "White"; Td.width= "30"; }    }}

2. Background Thread code, placed in a JS file

onmessage=function(event) {    var intarray=New Array (+);      for (var i=0;i<100;i++) {        intarray[i]=parseint (math.random () *100);    }     var worker=New worker ("Worker2.js");    Worker.postmessage (Json.stringify (Intarray));    Worker.onmessage=function(event) {            postMessage (event.data);    }}

The PostMessage method of the child thread object is used when the message is submitted to the child thread, and the PostMessage method is used directly when sending the message to the creation source of the thread.

3. Sub-thread code, placed in a JS file

 onmessage = function   var  intarray = Json.parse (event.data);     var   Returnstr;    Returnstr  = "" ;  for  (var  i=0;i< Intarray.length;i++ if  (parseint ( Intarray[i])%3 = = 0 if  (returnstr!= " "" {returnstr  + = ";"         returnstr  +=intarray[i];    }} postMessage (RETURNSTR); Close ();}  

Note: After sending a message back to the sending source in a child thread, it is best to use the close statement to close the child thread if the child thread is no longer in use.

Vi. interacting with data in multiple sub-threads

To implement the interaction between a child thread and a child thread, the following steps are required:

1) Create a child thread that sends the data first.

2) perform the tasks in the sub-thread and send the data to the main thread.

3) When the main thread receives a message from the path back, it creates a child thread that receives the data, and then passes the message returned in the child thread that sent the data to the child thread that receives the data.

4) Execute code in the receive data sub-thread.

1. Main thread Code

onmessage=function(event) {    var worker=New worker ("Worker1.js");    Worker.postmessage ("");    Worker.onmessage=function(event) {        var data = event.data;         New Worker ("Worker2.js");        Worker.postmessage (data);        Worker.onmessage=function(event) {            var data = event.data;            PostMessage (data);     }}}

2. Send data sub-thread code

onmessage=function(event) {    var intarray=New Array (+);      for (var i=0;i<100;i++) {        intarray[i]=parseint (math.random () *100);    }    PostMessage (Json.stringify (Intarray));    Close ();}

3. Receive data sub-thread code

onmessage=function(event) {    var intarray = json.parse (event.data);     var Returnstr;    Returnstr= "";      for (var i=0;i<intarray.length;i++) {        if(parseint (intarray[i])%3 = = 0) {             if (returnstr!= "") {                returnstr+ = ";")             }            returnstr+ =intarray[i];}    }    PostMessage (RETURNSTR);    Close ();}

Vii. variables, functions, and classes available in threads

    1. Self: Used to represent scopes within the scope of this thread
    2. PostMessage: Used to send a message to the source window where the thread was created
    3. OnMessage: Gets the event that receives the message
    4. Importscripts (URLs): Import other JavaScript script files. parameter is the URL address of the script file, you can import multiple script files. The imported script file must be in the same domain as the page that uses the thread file, and in the same port.
    5. Navigator object: Similar to the Window.navigator object, has a Appname,platform,useragent,appversion property.
    6. Sessionstorage/localstorage: You can use Web Storage in threads
    7. XMLHttpRequest: Ajax requests can be processed in the thread
    8. Web Workers: Threads can be nested inline
    9. Settimeout/setinterval: Timed processing can be implemented in the thread
    10. Close: Used to end this thread
    11. Eval,isnan,escape and so on can use all JavaScript core functions
    12. Object: You can create and use local objects
    13. Websockets: You can use the Websockets API to send and receive messages to the server
    14. FileSystem: Create, update, and delete files and directories in a sandbox-protected file system by synchronizing the FileSystem API in a thread

Viii. Use of Sharedworker

1. Create a Sharedworker object

var New Sharedworker (Url,[name]);

The first parameter specifies the URL address of the background script file, and the second parameter is an optional parameter that specifies the name of the worker.

var New Sharedworker (' test.js ');

2. When the Sharedworker object is created, a Messageport object is created at the same time, and can be accessed through the port property of the Sharedworker object, which represents the window to be used when the page communicates, with three methods as shown below:

PostMessage method: Used to send a message to another page

Start method: Used to activate the port and start listening on whether the port received the message

Close method: Used to close and deactivate a window

Each Messageport object has a message event that is triggered when a message is received by the port.

You can specify the processing that is done when the message is received by listening on the message event of the Messageport object and specifying the method of the event handler.

port.onmessage=function(event) {    // processing received message }

The trigger of the message event can also be monitored by the AddEventListener method of the Messageport object, but in this case the Start method of the Messageport object must be used to explicitly activate the port, starting the listener

function (event) {    // processing received message },false);p Ort.start ();

3. When a page starts communicating with a shared background thread through the Sharedworker object, the Connect event of the background thread object is triggered, the event is monitored and the processing is defined in the background script file to trigger the event

onconnect=Function (event) {    // define event handler }

In the event handler function, the value of the port property for the event parameter value (which represents the triggered events object) is a collection where the first array is the Port property value of the Sharedworker object in that page. The Messageport object that represents the port on which the page is used to send or get messages.

onconnect=function(e) {    var port=e.ports[0];    Port.onmessage=function(e) {        port.postmessage (e.data*e.data);}    }

Reference book: The authoritative guide for HTML5 and CSS3

Sample code can go to my github download: Https://github.com/sakuramoon0203/Web-Worker

On Web Workers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.