"JavaScript" Thread Webworker

Source: Internet
Author: User

Introduced

By using Webworker, we can run JavaScript in the background of the browser without taking up the browser's own thread. Webworker can improve the overall performance of your application and improve the user experience. If you want to use Webworker in your Web app, here are 7 things to know about Webworker.

1.WebWorker Allows you to run JavaScript in the background

In general, JavaScript and the UI of the page will share a thread, so when you click a button to start running JavaScript, the page will not be able to respond to user actions until this code is finished, and in other words it is "Frozen". While this code can be handed to Webworker to run in the background, the page can still respond to user actions while the JavaScript is running. A worker thread is started in the background to execute this code, and the user can create multiple worker threads. So you can do some work on small scale distributed computing at the front desk, but Webworker has the following usage restrictions:

    • Webworker cannot access DOM nodes;
    • Webworker cannot access global variables or global functions;
    • Webworker cannot invoke a function such as alert () or confirm;
    • Webworker cannot access browser global variables such as window or document;

However, JavaScript in Webworker can still use functions such as settimeout (), setinterval (), or use XMLHttpRequest objects to do AJAX communication.

2. There are two kinds of webworker

Webworkers can be divided into two types: dedicated thread Dedicatedwebworker, and shared threading Sharedwebworker. Dedicatedwebworker ends with the closing of the current page, which means that dedicatedwebworker can only be accessed by the page that created it. The corresponding sharedwebworker can be accessed by multiple pages. In JavaScript code, the "work" type represents dedicatedwebworker, and the "Sharedworker" type represents Sharedwebworker.

In the vast majority of cases, using dedicatedwebworker is sufficient, because the code that is generally run in Webworker is designed to serve the current page. In some specific cases, webworker may run a more generic code that can serve multiple pages. In this case, we will create a shared thread sharedwebworker, which can be accessed by multiple pages associated with it, and the sharedwebworker will not end until all associated pages are closed. The relative dedicatedwebworker,sharedwebworker is slightly more complicated.

3. The Worker "Object represents Dedicatedwebworker

Now let's see how to use Dedicatedwebworker. The following example uses jquery and Modernizr as the JavaScript library, and then adds the following code to the HTML page:

[HTML]

  1. <! Doctypehtml>
  2. <title></title>
  3. <scripttype= "Text/javascript" src= "Script/modernizr.js" ></script>
  4. <scripttype= "Text/javascript" src= "Script/jquery-2.0.0.js" ></script>
  5. <scripttype= "Text/javascript" >
  6. $ (document). Ready (function () {
  7. if (! Modernizr.webworker) {
  8. Alert ("Thisbrowserdoesn ' tsupportwebworker!");
  9. Return
  10. }
  11. $ ("#btnStart"). Click (function () {
  12. Varworker=newworker ("Script/lengthytask.js");
  13. Worker.addeventlistener ("Message", function (evt) {
  14. alert (evt.data);
  15. },false);
  16. Worker.postmessage (10000)
  17. });
  18. });
  19. </script>
  20. <body>
  21. <form>
  22. <inputtype= "button" id= "Btnstart" value= "startprocessing"/>
  23. </form>
  24. </body>

There is a button in this HTML page that will run a JavaScript file when clicked. The above code first detects whether the current browser supports Webworker, and does not support it, and jumps out of the alert message.

The button's Click event creates a Worker object and assigns it a JavaScript script file,--lengthytask.js (with code later), and binds a "message" event to the Worker object. This event is triggered when the background code (LENGTHYTASK.JS) returns data to the page. The "message" event can be event.data to get back the data returned by the backend code. Finally, the PostMessage method formally executes the lengthytask.js, which can also pass parameters to the backend code, which is also obtained by the background code through the message event.

Here is the code that lengthytask.js mainly contains:

[JavaScript]

    1. AddEventListener ("Message", function (evt) {
    2. Vardate=newdate ();
    3. Varcurrentdate=null;
    4. do{
    5. Currentdate=newdate ();
    6. }while (Currentdate-date<evt.data);
    7. PostMessage (currentdate);
    8. },false);

The above code listens to the message time in the background and gets the parameters of the page: 10000; Here is actually a timing function: After the message event is triggered for 10000 milliseconds, the result (currentdate) is passed to the page.

So when you click on the "Startprocessing" button, the page will alert you at the moment after 10 seconds. The page can still respond to mouse keyboard events within 10 seconds.

4. "Sharedworker" object represents Sharedwebworker

The preceding code uses Dedicatedwebworker. This section uses Sharedwebworker instead of dedicatedwebworker to differentiate between the two. The following is the Sharedwebworker version of the same example:

[JavaScript]

    1. AddEventListener ("Message", function (evt) {
    2. Vardate=newdate ();
    3. Varcurrentdate=null;
    4. do{
    5. Currentdate=newdate ();
    6. }while (Currentdate-date<evt.data);
    7. PostMessage (currentdate);
    8. },false);

Note The black code, where a Sharedworker object is created and the message event is bound to the Port object of Sharedworker, and the Port object is also the initiator of the postmessage. Begins the execution of the background code sharedlengthytask.js.

Here is the main code for Sharedlengthytask.js:

[JavaScript]

    1. Varport;
    2. AddEventListener ("Connect", function (evt) {
    3. Port=evt.ports[0];
    4. Port.addeventlistener ("Message", function (evt) {
    5. Vardate=newdate ();
    6. Varcurrentdate=null;
    7. do{
    8. Currentdate=newdate ();
    9. }while (Currentdate-date<evt.data);
    10. Port.postmessage (currentdate);
    11. },false);
    12. Port.start ();
    13. },false);

Background code that uses the Sharedworker object needs to bind the Connect and message events, and the Connect event is triggered when port on the page is start. The callback function for the subsequent message event is essentially the same as before, and the last port calls the PostMessage method to pass the result back to the page.

5.WebWorker using XMLHttpRequest to communicate with the server

In some cases, webworker also needs to interact with the server. For example, the page may need to process information from the database, we need to use AJAX technology to interact with the server, the following code contains webworker how to get data from the service side:

[JavaScript]

    1. AddEventListener ("Message", function (evt) {
    2. Varxhr=newxmlhttprequest ();
    3. Xhr.open ("GET", "lengthytaskhandler.ashx");
    4. Xhr.onload=function () {
    5. PostMessage (Xhr.responsetext);
    6. };
    7. Xhr.send ();
    8. },false);

The above code makes a GET request to the service-side ASP. Lengthytaskhandler.ashx. and registers the OnLoad event after getting the data. The following code is the service-side lengthytaskhandler.ashx:

[CSharp]

    1. Namespacewebworkerdemo
    2. {
    3. Publicclasslengthytaskhandler:ihttphandler
    4. {
    5. Publicvoidprocessrequest (Httpcontextcontext)
    6. {
    7. System.Threading.Thread.Sleep (10000);
    8. Context. Response.contenttype= "Text/plain";
    9. Content. Response.Write ("processingsuccessful!");
    10. }
    11. Publicboolisreusable
    12. {
    13. Get
    14. {
    15. Returnfalse;
    16. }
    17. }
    18. }
    19. }

As you can see, ProcessRequest simulates a long-running task and returns "processingsuccessful! "Message.

6. capturing error messages via the error event

The error handling mechanism is essential when we add more and more complex logic to the webworker. Instead, Webworker provides error events for developers to catch the wrong message. The following code shows how to bind the Error event:

[JavaScript]

    1. $ ("#btnStart"). Click (function () {
    2. Varworker=newworker ("Scripts/lengthytask.js");
    3. Worker.addeventlistener ("Error", function (evt) {
    4. Alert ("line#" +evt.lineno+ "-" +evt.message+ "in" +evt.filename);
    5. },false);
    6. Worker.postmessage (10000);
    7. });

As seen above, the worker object can bind the error event, and the Evt object contains the code file (evt.filename) where the error resides, the number of lines of code where the error is located (Evt.lineno), and the error message (evt.message).

7. terminate Webworker via the Terminate () method

In some cases, we may need to force termination of webworker in execution. The Worker object provides terminate () to terminate its own execution of the task, the terminated worker object cannot be restarted or reused, and we can only create another worker instance to perform the new task.

Summarize

Webworker can execute scripts in the background without blocking page interaction. There are two types of worker objects: dedicated Webworker and shared Webworker: Dedicated webworker can only be used as a single page, while shared webworker may be used by multiple pages. In addition, this article describes the error handling mechanism of Webworker and the use of Ajax to interact with the server.

Related Article

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.