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
- <! DOCTYPE HTML>
- <html>
- <head>
- <title></title>
- <script type="Text/javascript" src="Script/modernizr.js"></script >
- <script type="Text/javascript" src="Script/jquery-2.0.0.js"></ Script>
- <script type="Text/javascript">
- $ (document). Ready (function () {
- if (! Modernizr.webworker) {
- Alert ("This browser doesn ' t-support Web worker!");
- Return
- }
- $ ("#btnStart"). Click (function () {
- var worker = new Worker ("Script/lengthytask.js");
- Worker.addeventlistener ("Message", function (evt) {
- alert (evt.data);
- }, False);
- Worker.postmessage (10000)
- });
- });
- </Script>
- </head>
- <body>
- <form>
- <input type="button" id="btnstart" value="Start processing"/>
- </form>
- </body>
- </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
- AddEventListener ("message", function (evt) {
- var date = new Date ();
- var currentdate = null;
- do {
- currentdate = new Date ();
- }while (Currentdate-date < evt.data);
- PostMessage (currentdate);
- }, 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
- AddEventListener ("message", function (evt) {
- var date = new Date ();
- var currentdate = null;
- do {
- currentdate = new Date ();
- }while (Currentdate-date < evt.data);
- PostMessage (currentdate);
- }, 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
- var port;
- AddEventListener ("Connect", function (evt) {
- Port = evt.ports[0];
- Port.addeventlistener ("message", function (evt) {
- var date = new Date ();
- var currentdate = null;
- do {
- currentdate = new Date ();
- }while (Currentdate-date < evt.data);
- Port.postmessage (currentdate);
- }, false);
- Port.start ();
- }, 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
- AddEventListener ("message", function (evt) {
- var xhr = new XMLHttpRequest ();
- Xhr.open ("GET", "lengthytaskhandler.ashx");
- Xhr.onload = function () {
- PostMessage (Xhr.responsetext);
- };
- Xhr.send ();
- },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
- Namespace Webworkerdemo
- {
- Public class Lengthytaskhandler:ihttphandler
- {
- Public void ProcessRequest (HttpContext context)
- {
- System.Threading.Thread.Sleep (10000);
- Context. Response.ContentType = "Text/plain";
- Content. Response.Write ("Processing successful!");
- }
- Public bool IsReusable
- {
- Get
- {
- return false;
- }
- }
- }
- }
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
- $ ( function () {
- var worker = new worker (
- worker.addeventlistener (function (evt) {
- alert (" - " + evt.message + " in " + evt.filename";
- }, false);
- 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