Deep analysis HTML5 Web worker is a tool or a device

Source: Internet
Author: User
Tags script tag sleep

One, about Web Worker

HTML5 several advantage features, including web worker, this product can be understood as multithreading, in normal conditions, the browser to execute a piece of the program will block until the end of the return to the normal state, and HTML5 web worker is to solve this problem.
So it can solve two problems: first, solve the problem of blocking the program, second, improve efficiency.

Second, examples

Usually the most common test efficiency is Fibonacci, we also have a Fibonacci performance test.


var start = (new Date ()). GetTime ();
var Fibonacci =function (N) {
Return n<2? N:arguments.callee (n-1) + Arguments.callee (n-2);
};
Fibonacci (38);
Console.log (New Date ()). GetTime ()-start);
Console.log played 4792

Each computer performance is not the same, the browser may be different, 38 implementation needs to close to 5s, two times is almost 10s.


Fibonacci (38);
Fibonacci (38);
Two execution required 9694

We introduce web Worker, improve efficiency, shorten the operation time difference


var start = (new Date ()). GetTime ();

Instantiate a worker instance, the parameter must be a JavaScript script
var worker = new Worker (' worker.js ');

Monitor worker Communications
Worker.addeventlistener (' message ', function (event) {
Console.log (' Worker result: ' + (new Date ()). GetTime ()-start);
}, False);


Post data to worker
Worker.postmessage (38);


var Fibonacci =function (N) {
Return n<2? N:arguments.callee (n-1) + Arguments.callee (n-2);
};

There is only one left on the main page and the other one has been transferred to the worker for execution.
settimeout (function () {
Fibonacci (38);
Console.log (New Date ()). GetTime ()-start);
}, 100);

Worker.js


var Fibonacci =function (N) {
Return n<2? N:arguments.callee (n-1) + Arguments.callee (n-2);
};

Self.addeventlistener (' message ', function (event) {
Self.postmessage (Fibonacci (Event.data))
}, False);
Execution results:
1
2
5394
Script.js:9 Worker result:5399


Third, packaging


But if you want to do several consecutive things, you can't do this:


Worker.postmessage (38);
Worker.postmessage (38);
Worker.postmessage (38);

Because it's just a new worker, so it will be executed sequentially:


Script.js:26 5369
Script.js:9 Worker result:5374
Script.js:9 Worker result:9960
Script.js:9 Worker result:14557

We can new multiple at the same time


var start = (new Date ()). GetTime ();

var Fibonacci =function (N) {

Instantiate a worker instance, the parameter must be a JavaScript script
var worker = new Worker (' worker.js ');

Monitor worker Communications
Worker.addeventlistener (' message ', function (event) {
Console.log (' Worker result: ' + (new Date ()). GetTime ()-start);
}, False);

Post data to worker
Worker.postmessage (n);
};

Fibonacci (38);
Fibonacci (38);
Fibonacci (38);

Execution results:


Worker result:7062
Worker result:7068
Worker result:7128

4 Results performed:


Script.js:11 Worker result:9323
Script.js:11 Worker result:9335
Script.js:11 Worker result:9340
Script.js:11 Worker result:9350
The more visible instances, the higher the efficiency of a single execution, since a new worker can be time-consuming, but even this is more efficient than blocking sequentially execution in the browser.


Iv. cross-domain and scripting introduction


A worker must pass in a script URL when instantiated, and must be under this domain, otherwise it will report a cross-domain error:
This field: http://localhost:63342/

var worker = new Worker (' http://localhost/worker.js ');
Report Security Error:
Uncaught securityerror:failed to construct ' Worker ': Script in ' http://localhost/worker.js ' cannot be accessed from Origi N ' http://localhost:63342 '.
But you can use the Importscripts method in the worker to introduce any domain script, just like the script tag in HTML
Http://localhost/script.js


Console.log (' Hello world! from Http://localhost/script.js ');

The worker introduces it.


Self.importscripts (' http://localhost/script.js ');
Console.log:Hello world! From Http://localhost/script.js
is new Worker and importscripts asynchronous or synchronized? Do a test.
Python Code


Class Worker (Tornado.web.RequestHandler):
def get (self):
Time.sleep (5)
Self.write ("" "
Console.log (' from worker ');
""")
Sleep 5 seconds, then return, console:


Script.js:1 start ....
Script.js:3 end!
Worker:2 from worker

No obstruction, then look at importscripts:
Worker.js

Self.importscripts ('/script1 ');
Self.importscripts ('/script2 ');
Python Code

Class Script1 (Tornado.web.RequestHandler):
def get (self):
Time.sleep (5)
Self.write ("" "
Console.log (' from script1 ');
""")


Class Script2 (Tornado.web.RequestHandler):
def get (self):
Self.write ("" "
Console.log (' from Script2 ');
""")
SCRIPT1 delay 5 Seconds to return, and then Console.log or sequentially print:


Start ....
end!
From SCRIPT1
From Script2
Timeline:

The red circle indicates that it is sequentially loaded


v. Debugging and browser support


Again the function of good, if not convenient debugging is also slag, fortunately, Chrome is very easy to debug

Mainstream browsers are supported by people who have been spurned by the IE10 also support the

Vi. weaknesses


Worker also has limitations, it can not operate the DOM, most of the JavaScript applications are currently processing DOM, the need for very large performance of the operation is usually put on the server side, otherwise the browser ran a tired of its script will let it pop out of the disgusting unresponsive.
Its API is very few, almost can count out, say a few very practical
1, XMLHttpRequest, with it, in order to issue an AJAX request
2, the most magical place of Settimeout/setinterval,js
3, importscripts, loading the external JS script in the worker
4, Addeventlistener/postmessage, with them in order to communicate with the homepage
Some children's shoes have said that there is no document API in the worker, so I get DOM objects from the homepage through the PostMessage past. First, it's futile.
Console will play:
Uncaught datacloneerror:failed to execute ' postMessage '-' Worker ': An object could is not cloned.
Even if you're good, you finally pass the object, but that's a copy of it, not the same memory address.


var obj = {};

Instantiate a worker instance, the parameter must be a JavaScript script
var worker = new Worker (' worker.js ');

Post data to worker
Worker.postmessage (obj);

Worker.addeventlistener (' message ', function (event) {
Console.log (event.data = = obj);
});
Worker.js

Self.addeventlistener (' message ', function (event) {
Self.postmessage (Event.data);
}, False);
Console:

False
In fact, it's normal to think about it, it's not possible to share the DOM, otherwise I'm operating here. Dom,worker is also operating the DOM, and even deleted the DOM, is this not a conflict?

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.