Reproduced What the hell is Webworker?

Source: Internet
Author: User

Objective

Front-end engineers must have had this experience, when a page loaded with a large number of JS files, the user interface may be briefly "frozen." This is well understood, because JS is a single-threaded language. We go to the extreme point, a section of JS appeared while () {} The Dead loop, then click on the page DOM element, will not trigger the event, in fact, these asynchronous events are queued, and so on the page JS After rendering to execute (from settimeout on the JavaScript operation Mechanism), and at this time the rendering into the dead loop, so the user interface has been "frozen" phenomenon.

While the actual development, although not similar to the dead loop, but a lot of JS rendering will affect the user experience, at this time we hope this time-consuming JS is best to execute asynchronously, SetTimeout is a good method, but H5 provides a better way, the Web worker! The WEB Worker specification solves this problem by letting Javascript run in the background. Browsers implement WEB Worker specifications in a number of ways, using threads, background processes, or processes running on other processor cores, and so on. The specifics of implementation details are less important, and it is important that developers can now safely run Javascript without worrying about the user experience.

Since the Worker is the H5 family, then IE6 can go aside, detailed browser compatibility can refer to http://caniuse.com/#search =worker

If there is no Worker

Let's look at this piece of code:

<Divstyle= ' width:100px;height:100px;background-color:red '></Div> <Script>Document.queryselector ('Div'). onclick= function() {Console.log ('Hello World');    }; functionFibonacci (n) {returnN< 2 ?N:arguments.callee (n- 1) +Arguments.callee (n- 2); } console.log (Fibonacci ( $)); </Script> 

A DIV is written on the page, and then it listens for its Click event, and in JS it needs to calculate the 36th of the Fibonacci sequence and output it. Such a page user experience is very poor, if Fibonacci do not finish, Div's Click event is not timely response, and recursive solution Fibonacci sequence items is quite time-consuming! Such a time-consuming JS code, to the worker to do just right!

To sacrifice a large killing device Worker.

The use of the Worker is simple.

Instantiate the Worker object and pass in the Javascript file name to execute to create a new Web Worker:

var New

This code causes the browser to download worker.js, but only the worker receives the message to actually execute the code in the file. To pass a message to the worker, you can use the PostMessage () method, such as the 36th item that I want to tell the worker to ask for the Fibonacci sequence:

Let's see how the Worker receives the message. When a page calls PostMessage () on a Worker object, the data is passed asynchronously to the worker, triggering a message event in the worker. To process data from a page, you also create a OnMessage event handler. (Worker.js code)

function (event) {   var data = event.data;   Console.log (Fibonacci (data)); };   function Fibonacci (n) {   return N < 2? N:arguments.callee (n-1) + Arguments.callee (n-2

Page can pass data to Worker,worker of course also can callback, page through message event to listen:

function (event) {   var data =

A Worker communicates with a page through the message and error events. Data from the Worker is saved in the Event.data. The error event is triggered when a Worker cannot complete a given task. Specifically, the Javascript inside the Worker will trigger an error event whenever it encounters errors during execution. When the error event occurs, the event object contains three properties: FileName, Lineno, and message, respectively, representing the wrong file name, code line number, and complete error message:

function (event) {   

We recommend that you write error events when working with workers, just as you would always write when using Ajax as a remedy for failure.

Full code:

HTML file:

<Divstyle= ' width:100px;height:100px;background-color:red '></Div> <Script>Document.queryselector ('Div'). onclick= function() {Console.log ('Hello World');    }; varworker= NewWorker ('Worker.js'); Worker.postmessage ( $); Worker.onmessage= function(event) {varData=Event.data;    Console.log (data)}; Worker.onerror= function(event) {Console.log (Event.filename, Event.lineno, event.message); }; </Script> 

Worker.js file:

function (event) {   var data = event.data;    var ans = Fibonacci (data);     This . PostMessage (ans);};   function Fibonacci (n) {   return N < 2? N:arguments.callee (n-1) + Arguments.callee (n-2

Simple summary:

Web Main thread:

    1. Load a JS file with var worker = new Worker (URL) to create a worker and return a worker instance.
    2. Use the Worker.postmessage (data) method to send data to the worker.
    3. Binds the Worker.onmessage method to receive data sent by the worker.
    4. You can use Worker.terminate () to terminate the execution of a worker.

Worker New Thread:

    1. Bind the OnMessage method to receive the data sent by the mainline Cheng.
    2. Use the PostMessage (data) method to send data to the main thread.
    3. You can use Self.close () to terminate the execution of a worker.

Worker Other

With regard to Web Worker, it is important to know that the Javascript code that it executes is completely in the other scope and does not share the scope with the code in the current Web page. In a Web Worker, there is also a global object (the Worker object itself, this and self refer to the Worker object itself) and other objects as well as methods. The code in the Web Worker does not have access to the DOM. So what are the objects that the code in the Worker can access and what methods are available?

    1. Minimized navigator objects, including OnLine, AppName, AppVersion, useragent, and Platform properties
    2. Read-Only Location object
    3. SetTimeout (), SetInterval (), cleartimeout (), Clearinterval () method
    4. XMLHttpRequest constructor function

The Worker can be terminated at any time. In Worker.js, we can use the Self.close () method, and in the page we can use the Worker.terminal () method, when the error and message events are not triggered.

Reference: http://mdsa.51cto.com/art/201511/497002.htm

Reproduced What the hell is Webworker?

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.