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]
- <! Doctypehtml>
- <title></title>
- <scripttype= "Text/javascript" src= "Script/modernizr.js" ></script>
- <scripttype= "Text/javascript" src= "Script/jquery-2.0.0.js" ></script>
- <scripttype= "Text/javascript" >
- $ (document). Ready (function () {
- if (! Modernizr.webworker) {
- Alert ("Thisbrowserdoesn ' tsupportwebworker!");
- Return
- }
- $ ("#btnStart"). Click (function () {
- Varworker=newworker ("Script/lengthytask.js");
- Worker.addeventlistener ("Message", function (evt) {
- alert (evt.data);
- },false);
- Worker.postmessage (10000)
- });
- });
- </script>
- <body>
- <form>
- <inputtype= "button" id= "Btnstart" value= "startprocessing"/>
- </form>
- </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]
- AddEventListener ("Message", function (evt) {
- Vardate=newdate ();
- Varcurrentdate=null;
- do{
- Currentdate=newdate ();
- }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 "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]
- AddEventListener ("Message", function (evt) {
- Vardate=newdate ();
- Varcurrentdate=null;
- do{
- Currentdate=newdate ();
- }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 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]
- Varport;
- AddEventListener ("Connect", function (evt) {
- Port=evt.ports[0];
- Port.addeventlistener ("Message", function (evt) {
- Vardate=newdate ();
- Varcurrentdate=null;
- do{
- Currentdate=newdate ();
- }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.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]
- AddEventListener ("Message", function (evt) {
- Varxhr=newxmlhttprequest ();
- 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]
- Namespacewebworkerdemo
- {
- Publicclasslengthytaskhandler:ihttphandler
- {
- Publicvoidprocessrequest (Httpcontextcontext)
- {
- System.Threading.Thread.Sleep (10000);
- Context. Response.contenttype= "Text/plain";
- Content. Response.Write ("processingsuccessful!");
- }
- Publicboolisreusable
- {
- Get
- {
- Returnfalse;
- }
- }
- }
- }
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]
- $ ("#btnStart"). Click (function () {
- Varworker=newworker ("Scripts/lengthytask.js");
- Worker.addeventlistener ("Error", function (evt) {
- Alert ("line#" +evt.lineno+ "-" +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. 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.