The emerging ECMAScript Api--web Worker

Source: Internet
Author: User

As weall know, JavaScript is single-threaded , JS and UI updates share the same process in part because of frequent visits between them, but because the sharing of the same process will cause the JS code when the user clicks the interface element without any response to this situation, How could such a bad user experience HTML5 not be revised so that the Web worker was born.

When the Web worker process loads JS, it does not affect the browser UI, nor does it affect the JS code that is loaded by other web worker processes. Because the Web worker process loading JS runtime does not affect the browser UI, it also means that the Web worker loading JS can not modify the user interface, and each Web worker has its own global environment, because it loaded JS can not modify the user interface, So the objects it can manipulate consist mainly of the following parts

    • A browser object that contains only four properties: Appname,appversion,useragent,platform
    • A Location object (as in window, but all of the properties are read-only)
    • A self object points to the global web worker thread object
    • A importscripts () method enables web worker to load external JS files
    • All the ECMAScript objects
    • XMLHttpRequest Constructors
    • SetTimeout () and SetInterval () methods

Here is a importscript method, which is loaded with the blocking method JS, only after all the files are loaded, the next script can continue to run

In fact,WEB workers are suitable for long-running scripts that are purely data-or that are not related to the browser's UI.

The following is the most basic demo case, I believe you can see the smart

Simply create an HTML page with the page code shown below

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head>    <title></title></Head><Body>    <Scripttype= "Text/javascript">        varworker= NewWorker ("Webworker.js"); //This sentence will allow the browser to load Webworker.jsWorker.postmessage ('The main thread initiates the data request!'); //Pass the data to Webworker.jsWorker.onmessage= function(event) {Console.log (event.data);//data from work is saved in Event.data            //the next step is to serialize and event.data the data.        }; </Script></Body></HTML>

The code for the Webworker.js code loaded above is as follows:

OnMessage =function(event) {vardata = Event.data;//This is the data received.Console.log (data);//Note that it is not possible to replace console.log with alert because alert is blocking the UI, so Wobworker does not have permission to use alert.PostMessage (data + '---js replies come back to the statistics Oh! ');//here, you can pass the data to the main thread .};onerror=function(event) {Console.log (' Error: ' + event.filename + ' (' + Event.lineno + '): ' +event.message); //event.filename the wrong file name    //Event.lineno The line number of the error    //event.message complete error message}

So what is the main use of web workers, and what are the advantages of it, the following summary of HA

    • Can load a JS for a large number of complex computations without suspending the main process and communicating through Postmessage,onmessage, using the Ternimate method to stop working
    • Additional script files can be loaded in worker via Importscripts (URL)

Where is the main drawback?

    • Cannot load JS across domains
    • In-worker code cannot access the DOM
    • Because it's a new API in HTML5, the browser support is different!

Web worker to load data is still slow, even if it is a large data volume without any advantage, it may be the worker initializes the new thread compared time. There is no advantage other than blocking during the loading process

Here is another example I wrote, mainly to play web worker's expertise

The HTML interface code looks like this

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head>    <title></title></Head><Body>    <Scripttype= "Text/javascript">        varworker= NewWorker ('Fibonacci.js'); Worker.addeventlistener ('message', function(event) {Console.time ('The total time spent is:'); Console.log ('Results:' +event.data); Console.timeend ('The total time spent is:'); }, false); Worker.postmessage ( +); </Script></Body></HTML>

The Fibonacci.js code loaded in the above code is shown below

var function (n) {    return N < 2 N:arguments.callee (n-1) + Arguments.callee (n-2function
     (event) {    var n = parseint (Event.data, ten);    Console.log (' The value passed is: ' +n ');     function (event) {    console.log (' Error: ' + event.filenme + ' (' + Event.lineno + '): ' + event.message);}

You can find the results of the chrome console after you run it as shown:

Just write here, what advice or do not understand the place to contact me!

The emerging ECMAScript Api--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.