7 things you need to know about web worker

Source: Internet
Author: User

Introduced

By using Web Worker, we can run JavaScript in the background of the browser without consuming the browser's own thread. WEB workers can improve the overall performance of your app and improve the user experience. If you want to use Web workers in your Web app, here are 7 things to know about web worker.

1. Web Worker 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". This code can be left to the Web worker to run in the background, and 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 web worker has the following restrictions:

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

However, JavaScript in Web worker can still use functions such as settimeout (), setinterval (), or use XMLHttpRequest objects for AJAX communication.

2. There are two types of Web Worker

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 "work" type represents dedicated web worker, and the "Sharedworker" type represents a shared web worker.

In the vast majority of cases, it is sufficient to use dedicated web worker, because the code that runs in the Web worker generally is designed to serve the current page. In some specific cases, a Web worker might run a more general code that can serve multiple pages. In this case, we will create a shared web worker that shares a thread, which can be accessed by multiple pages associated with it, and the shared web worker ends only when all the associated pages are closed. The relative dedicated web worker,shared Web worker is slightly more complex.

3. The "Worker" object represents the dedicated Web Worker

Now look at how to use the dedicated web worker. The following example uses jquery and Modernizr as the JavaScript library, and then adds the following code to the HTML page:

[HTML]View Plaincopy
  1. <! DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title></title>
  5. <script type="Text/javascript" src="Script/modernizr.js"></script >
  6. <script type="Text/javascript" src="Script/jquery-2.0.0.js"></ Script>
  7. <script type="Text/javascript">
  8. $ (document). Ready (function () {
  9. if (! Modernizr.webworker) {
  10. Alert ("This browser doesn ' t-support Web worker!");
  11. Return
  12. }
  13. $ ("#btnStart"). Click (function () {
  14. var worker = new Worker ("Script/lengthytask.js");
  15. Worker.addeventlistener ("Message", function (evt) {
  16. alert (evt.data);
  17. }, False);
  18. Worker.postmessage (10000)
  19. });
  20. });
  21. </Script>
  22. </head>
  23. <body>
  24. <form>
  25. <input type="button" id="btnstart" value="Start processing"/>
  26. </form>
  27. </body>
  28. </html>

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 Web Worker, and if not, 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]View Plaincopy
    1. AddEventListener ("message", function (evt) {
    2. var date = new Date ();
    3. var currentdate = null;
    4. do {
    5. currentdate = new Date ();
    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 "Start Processing" 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. The "Sharedworker" object represents the shared Web Worker

The preceding code uses the dedicated web worker. This section uses the shared web worker instead of the dedicated web worker to differentiate between the two. The following is a shared web worker version of the same example:

[JavaScript]View Plaincopy
    1. AddEventListener ("message", function (evt) {
    2. var date = new Date ();
    3. var currentdate = null;
    4. do {
    5. currentdate = new Date ();
    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 the shared worker, and the PostMessage is also initiated by the Port object. Begins the execution of the background code sharedlengthytask.js.

Here is the main code for Sharedlengthytask.js:

[JavaScript]View Plaincopy
  1. var port;
  2. AddEventListener ("Connect", function (evt) {
  3. Port = evt.ports[0];
  4. Port.addeventlistener ("message", function (evt) {
  5. var date = new Date ();
  6. var currentdate = null;
  7. do {
  8. currentdate = new Date ();
  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. Web worker uses XMLHttpRequest to communicate with server

In some cases, web worker 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 how the Web worker gets the data from the service side:

[JavaScript]View Plaincopy
    1. AddEventListener ("message", function (evt) {
    2. var xhr = new XMLHttpRequest ();
    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]View Plaincopy
  1. Namespace Webworkerdemo
  2. {
  3. Public class Lengthytaskhandler:ihttphandler
  4. {
  5. Public void ProcessRequest (HttpContext context)
  6. {
  7. System.Threading.Thread.Sleep (10000);
  8. Context.  Response.ContentType = "Text/plain";
  9. Content.  Response.Write ("Processing successful!");
  10. }
  11. Public bool IsReusable
  12. {
  13. Get
  14. {
  15. return false;
  16. }
  17. }
  18. }
  19. }


As you can see, ProcessRequest simulates a long-running task and returns "Processing successful! "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 Web worker. The Web worker provides the error event for the developer to catch the wrong message. The following code shows how to bind the Error event:

[JavaScript]View Plaincopy
    1. $ ( function () {  
    2. var worker =  new worker (
    3. worker.addeventlistener (function (evt) {  
    4. alert ("  -   " + evt.message + "  in  " + evt.filename";   
    5. }, false);   
    6. Worker.postmessage (10000);   


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. Terminating Web Worker through the Terminate () method

In some cases, we may need to force the termination of the Web Worker 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

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

7 things you need to know about web worker

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.